繁体   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