簡體   English   中英

缺點如何在Haskell中工作:

[英]How does cons work in Haskell :

在第二個例子中,缺點似乎沒有像我期望的那樣起作用。 我錯過了什么?

這里cons為列表添加了一個元素,這很棒。

1:[2,3]

但是有了這個,它似乎將第一個元素放入列表x並將尾部放入列表xs:

let { myInt :: [Int] -> [Int] ; myInt (x:xs) = xs }

我真的不明白為什么會發生這種情況,是否與遞歸有關?

提前致謝!

:運算符可用於構造列表和解構列表,具體取決於您使用它的位置。 如果在表達式中使用它,它就像用於構造列表一樣,就像你說的那樣。 當你在一個模式中使用它時,它會反過來 - 它解構(拆分)一個列表。

構建列表:

λ> 1:2:[3, 4]
[1,2,3,4]

解構清單:

λ> let first:second:rest = [1, 2, 3, 4]
λ> first
1
λ> second
2
λ> rest
[3, 4]

這同樣適用於Haskell中的許多數據構造函數。 您可以使用Just構造Maybe值。

λ> let name = Just "John"
λ> :type name
name :: Maybe [Char]

但是,您也可以使用它來拆分Maybe值。

λ> let Just x = name
λ> x
"John"

這里發生了兩件不同的事情。 您的第一個示例使用(:)運算符從元素1和列表[2,3]創建新列表。

1:[2,3]

您的第二個示例使用模式匹配 表達方式...

myInt (x:xs) = ...

...基本上說“如果myInt的參數由一個(可能是空的)列表前面的元素組成,那么讓我們調用第一個元素x和列表xs 。” 這個例子可以使它更清晰:

λ> let { myInt :: [Int] -> String ; myInt (x:xs) = "The first element is " ++ show x ++ " and the rest of the list is " ++ show xs}
λ> myInt [1,2,3]
"The first element is 1 and the rest of the list is [2,3]"

請注意,這僅在輸入列表包含至少一個元素時才有效。

λ> myInt []
"*** Exception: <interactive>:9:34-127: Non-exhaustive patterns in function myInt

但是,我們可以處理輸入列表為空的情況,如下所示:

λ> let { myInt :: [Int] -> String ; myInt (x:xs) = "The first element is " ++ show x ++ " and the rest of the list is " ++ show xs; myInt _ = "empty list"}
λ> myInt []
"empty list"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM