Functor fmap,模式匹配函数值,haskell [英] Functor fmap, pattern match function values, haskell
本文介绍了Functor fmap,模式匹配函数值,haskell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下类型,并希望将其设置为仿函数:
I have the following type, and would like to make it a Functor:
newtype SubsM a = SubsM {runSubsM :: Context -> Either Error (a, Env)}
到目前为止,我知道了
instance Functor SubsM where
fmap f (SubsM a) = SubsM (\s->(Right((f a),(fst s))))
我收到一个错误,因为a不是期望的类型,我的问题是我该如何在左侧匹配一个模式?
I get an error because a is not the expected type, my question is how do i pattern match a on the left-hand side?
推荐答案
您可以使用case
在Either Error (a, Env)
上进行模式匹配:
You can pattern match on the Either Error (a, Env)
with case
:
instance Functor SubsM where
fmap f (SubsM cf) = SubsM $ \c -> case (cf c) of
Left err -> Left err
Right (v, env) -> Right (f v, env)
在Left
情况下,您传播错误;在Right
情况下,将结果对拆包,并将f
应用于第一个元素.
In the Left
case you propagate the error, in the Right
case you unpack the resulting pair and apply f
to the first element.
这篇关于Functor fmap,模式匹配函数值,haskell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文