简体   繁体   English

缺点如何在Haskell中工作:

[英]How does cons work in Haskell :

Cons doesn't seem to work as I would expect in the second example. 在第二个例子中,缺点似乎没有像我期望的那样起作用。 What am I missing? 我错过了什么?

Here cons adds an element to a list, which is great. 这里cons为列表添加了一个元素,这很棒。

1:[2,3]

But with this one it seems to put the first element into list x and the tail into list xs: 但是有了这个,它似乎将第一个元素放入列表x并将尾部放入列表xs:

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

I don't really see why this would happen, is it something to do with recursion? 我真的不明白为什么会发生这种情况,是否与递归有关?

Thanks in advance! 提前致谢!

The : operator can be used to both construct a list and deconstruct a list, depending on where you use it. :运算符可用于构造列表和解构列表,具体取决于您使用它的位置。 If you use it in an expression, it is used for constructing a list, just like you said. 如果在表达式中使用它,它就像用于构造列表一样,就像你说的那样。 When you use it in a pattern, it does the reverse – it deconstructs (takes apart) a list. 当你在一个模式中使用它时,它会反过来 - 它解构(拆分)一个列表。

Constructing a list: 构建列表:

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

Deconstructing a list: 解构清单:

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

The same applies for many data constructors in Haskell. 这同样适用于Haskell中的许多数据构造函数。 You can use Just to construct a Maybe value. 您可以使用Just构造Maybe值。

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

However, you could also use it to take apart a Maybe value. 但是,您也可以使用它来拆分Maybe值。

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

There are two different things happening here. 这里发生了两件不同的事情。 Your first example uses the (:) operator to create a new list from the element 1 and the list [2,3] . 您的第一个示例使用(:)运算符从元素1和列表[2,3]创建新列表。

1:[2,3]

Your second example uses pattern matching . 您的第二个示例使用模式匹配 The expression... 表达方式...

myInt (x:xs) = ...

...essentially says "if the argument of myInt consists of an element prepended to a (possibly empty) list, then let's call the first element x and the list xs ." ...基本上说“如果myInt的参数由一个(可能是空的)列表前面的元素组成,那么让我们调用第一个元素x和列表xs 。” This example may make it clearer: 这个例子可以使它更清晰:

λ> 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]"

Note that this will only work if the input list contains at least one element. 请注意,这仅在输入列表包含至少一个元素时才有效。

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

However, we can handle the case where the input list is empty like this: 但是,我们可以处理输入列表为空的情况,如下所示:

λ> 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