我曾多次试图理解Haskell的函子和Monad,但我失败了。这一次,当我到达LYAH的应用函子时,我认为我理解Applicative typeclasses,但是我对应用实例实现有一些疑问,因为也许:
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> something = fmap f something对于上述片段的最后一行,我的理解如下:
(1) Just f在应用类定义的(<*>) :: f (a -> b) -> f a -> f b中被分配给f (a->b),f被分配给(a->b)。
(2) something被分配给f a。
我的问题来自于(2),为什么没有类似于Just something之类的东西?
在函数实例的实现中,有fmap f (Just x) = Just (f x)和Just x被分配给f a of fmap :: (a -> b) -> f a -> f b。
为了验证我的理解,我将something改为Just something
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> (Just something) = fmap f (Just something)在gchi的统治下,我试过
Just (+3) <*> Just 9 得到了同样的结果,Just 12,但当我尝试
Just (++"hahah") <*> Nothing` 我得到了错误
*** Exception: Functor.hs:(88,3)-(89,60): Non-exhaustive patterns in function <*>我不知道为什么或者我错过了什么?
发布于 2014-10-29 07:15:38
(这是我的评论的延伸,并没有真正回答这个问题)
这一备选定义更容易理解:
instance Applicative Maybe where
pure = Just
(Just f) <*> (Just x) = Just (f x)
_ <*> _ = Nothing我认为你掉进了一个陷阱,把something这个名字解释得太多了。我总是尝试在应用程序的上下文中命名变量f和x (准确地说,在<*>上下文中),这正是它们的本质,一个函数和一个应用函数的值。
发布于 2014-10-29 02:19:09
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> (Just something) = fmap f (Just something)我们只要看一下图案就能看出什么是不对的!第一个参数将匹配第一个参数为Nothing的任何参数,而第二个参数只有在两个参数都为Just ...时才匹配。没有比Just f和Nothing更好的了。仅仅因为第一个参数不是Nothing,并不意味着第二个参数必须是。如果您真的想要显式化,您可以在最后一行上面写_ <*> Nothing = Nothing。
https://stackoverflow.com/questions/26621326
复制相似问题