这个问题已经解决了,它是一个从字符串到“Maybe a”的Map,带有如下定义的空、插入、查找函数,我无法理解解决方案。
代码:
type Map a = String -> Maybe a
empty :: Map a
empty = \x -> Nothing
insert :: (String, a) -> Map a -> Map a
insert (s, a) m = \x -> if x == s then Just a else m x
lookup :: String -> Map a -> Maybe a
lookup x m = m x
我想我明白了。
但是insert对我来说很困惑,里面的lambda我不明白,当x从来没有被当作参数的时候,它是如何在等式中使用的,x是从我可以看到的字符串,但是它在任何地方都没有被赋予值。
还有,为什么像这样的一行可以工作并返回“Just 61”lookup "foo" (insert ("foo", 61) empty)
2条答案
按热度按时间9o685dep1#
当我们说
type Map a = String -> Maybe a
时,它只是一个类型别名,所以Map a
等同于String -> Maybe a
。因此,您知道Map a
只是一个函数类型String -> Maybe a
。因此,当我们说
empty :: Map a
时,我们想把empty
定义为从String
到Maybe a
的函数,在这个例子中,我们把它定义为\x -> Nothing
,这意味着empty
是一个空Map,它把每个字符串x
Map到Noting
。所以我们可以用同样的方法查看
insert :: (String, a) -> Map a -> Map a
,这个函数的意义就是多增加一个Map关系(即(String, a)
对)添加到给定的Map a
,并且返回值是包含添加的对的新的Map a
。因此,通过模式匹配insert (s, a) m
,s
是String
类型,a
的类型为a
,m
的类型为Map a
。现在我们要构造的结果的类型为Map a
。回想一下,Map a
就是String -> Maybe a
,所以我们要在这里构造一个函数。要构造函数,我们在这里使用lambda表达式。所以通过使用lambda表达式
\x -> if x == s then Just a else m x
,我们可以说这个新的Map a
(String -> Maybe a
类型的函数)接受String
x
,并检查它是否等于s
(这次插入的字符串)。如果不是s
,我们使用旧的Map a
(m
)来检查剩下的Map。该示例可计算为:
fnx2tebb2#
一个
Map a
是一个函数;x
是该函数的参数,在map中查找一个键就是调用该键上的map。考虑在Map中查找
"foo"
,然后将"foo"
Map到3
。现在考虑在同一Map中查找
"bar"
。