這個問題已經解決了,它是從字串到“Maybe a”的映射,具有如下定義的空、插入、查找函式,我無法理解解決方案。
編碼:
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 是如何在等式中使用的,x 來自我可以看到的字串,但沒有給出任何地方的價值。如何評估它的結果函式insert ("foo", 61) empty是什么,x 代表什么?
還有為什么這樣的行會起作用并回傳“Just 61”
lookup "foo" (insert ("foo", 61) empty)
uj5u.com熱心網友回復:
當我們說type Map a = String -> Maybe a時,它只是一個型別別名,所以Map a等同于String -> Maybe a。因此,您知道這Map a只是一個函式型別String -> Maybe a。
因此,當我們說 時empty :: Map a,我們希望將emptyfrom 定義為一個函式Stringto Maybe a。在此示例中,我們將其定義為\x -> Nothing,這意味著是將每個字串映射到empty的空映射。xNoting
所以我們可以考慮insert :: (String, a) -> Map a -> Map a使用相同的方法。這個函式的意思是在給(String, a)定的 上再增加一個映射關系(即pair)Map a,回傳值是一個新Map a的包含添加的pair。因此,通過模式匹配insert (s, a) m,sis of type String,ais of type a,mis of type 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)接受 a String x,并檢查它是否等于s(這次插入的字串)。如果不是s,我們使用舊的Map a( m) 來檢查剩余的映射。
該示例可以計算為:
lookup "foo" (insert ("foo", 61) empty)
{applying lookup}
= (insert ("foo", 61) empty) "foo"
{applying insert}
= (\x -> if x == "foo" then Just 61 else (empty x)) "foo"
{applying lambda expression, replacing x with "foo"}
= if "foo" == "foo" then Just 61 else (empty "foo")
{applying if_then_else}
= Just 61
uj5u.com熱心網友回復:
AMap a是一個函式;x是該函式的引數。在地圖中查找鍵僅意味著呼叫該鍵上的地圖。
考慮"foo"在映射中查找 而不是映射"foo"到3。
lookup "foo" (insert ("foo", 3) empty)
-- by the definition of lookup
== (insert ("foo", 3) empty) "foo"
-- by the definition of insert
== (\x -> if x == "foo" then Just 3 else empty x) "foo"
-- apply function to "foo"
== if "foo" == "foo" then Just 3 else empty "foo"
-- take the true branch
== Just 3
現在考慮"bar"在同一張地圖中查找 。
lookup "bar" (insert ("foo", 3) empty)
== (insert ("foo", 3) empty) "bar"
== (\x -> if x == "foo" then Just 3 else empty x) "bar"
== if "bar" == "foo" then Just 3 else empty "bar"
-- take the false branch
== empty "bar"
-- by definition of empty
== (\x -> Nothing) "bar"
-- apply function to "bar"
== Nothing
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528487.html
標籤:哈斯克尔拉姆达类型
上一篇:在撰寫結構時如何正確使用建構式以及Null的替代方法是什么?
下一篇:非詳盡模式例外
