Maybe(Haskell/LYAH)应用实例实现的定义
很多次我试图理解Haskell中的函子和单子,但都失败了。这一次,当我到达LYAH's时,我认为我理解了Maybe(Haskell/LYAH)应用实例实现的定义,haskell,Haskell,很多次我试图理解Haskell中的函子和单子,但都失败了。这一次,当我到达LYAH's时,我认为我理解了应用程序类型类,但我对应用程序实例的实现有一些疑问,可能是: instance Applicative Maybe where pure = Just Nothing <*> _ = Nothing (Just f) <*> something = fmap f something 在gchi下,我尝试了 Just (+3) <*> Just
应用程序类型类
,但我对应用程序实例的实现有一些疑问,可能是:
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> something = fmap f something
在gchi下,我尝试了
Just (+3) <*> Just 9
我弄错了
*** Exception: Functor.hs:(88,3)-(89,60): Non-exhaustive patterns in function <*>
***异常:Functor.hs:(88,3)-(89,60):函数中的非穷举模式
我不知道为什么或者我错过了什么 实例应用程序可能在哪里
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> (Just something) = fmap f (Just something)
纯粹的
没什么
(Just f)(Just something)=fmap f(Just something)
我们可以看到什么是错误的,只要看看模式!第一个参数将匹配第一个参数为Nothing
的任何对象,但第二个参数仅在同时为Just…
时匹配。没有匹配的只有f
和没有匹配的。仅仅因为第一个参数不是Nothing
,并不意味着第二个参数必须是。如果你真的想表达清楚,你可以在最后一行上面写\uunothing=Nothing
。(这是我评论的延伸,并没有真正回答问题)
这种替代定义更容易理解:
instance Applicative Maybe where
pure = Just
(Just f) <*> (Just x) = Just (f x)
_ <*> _ = Nothing
实例应用程序可能在哪里
纯粹的
(正f)(正x)=正(f x)
_什么都没有
我想你掉进了一个陷阱,对某个东西的名字解释得太多了。我总是尝试在应用程序的上下文中命名变量f
和x
(准确地说,在
的上下文中),这正是它们的名称,函数和函数所应用的值。(只是f)某物(只是f)(只是某物)
是不等价的something
只是一个变量,它与任何东西都匹配,包括构造函数Nothing
,而just something
不会与任何东西匹配。如果你也有而已uNothing=Nothing
,你的想法就会正确。然而,这是3行代码,程序员很懒,所以为什么要用3行代码写一些可以用2行代码写的东西?@user2407038,“匹配任何东西”你说的意思是包含的东西只是一些东西
?@user2407038“那么为什么要用3行代码写一些可以用2行代码写的东西呢?”意味着第2行中的\uuu
可以被某物
替换(当然,我已经使用第2行中的某物
对其进行了测试)?使用\uuu
的原因是懒惰?是的,模式某物将匹配仅x
<代码>.
与变量一样懒惰。因此,Nothing x=Nothing
的行为方式完全相同。\uu
的目的是向程序的读者传达没有使用该参数。问题写得好,感谢您的努力:-)
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> (Just something) = fmap f (Just something)
instance Applicative Maybe where
pure = Just
(Just f) <*> (Just x) = Just (f x)
_ <*> _ = Nothing