缺点如何在Haskell中工作:

Tim*_* UK 8 haskell

在第二个例子中,缺点似乎没有像我期望的那样起作用.我错过了什么?

这里cons为列表添加了一个元素,这很棒.

1:[2,3]
Run Code Online (Sandbox Code Playgroud)

但是有了这个,它似乎将第一个元素放入列表x并将尾部放入列表xs:

let { myInt :: [Int] -> [Int] ; myInt (x:xs) = xs }
Run Code Online (Sandbox Code Playgroud)

我真的不明白为什么会发生这种情况,是否与递归有关?

提前致谢!

kqr*_*kqr 11

:操作可用于两个构建列表和解构名单,这取决于你使用它.如果在表达式中使用它,它就像用于构造列表一样,就像你说的那样.当你在一个模式中使用它时,它会反过来 - 它解构(拆分)一个列表.

构建列表:

?> 1:2:[3, 4]
[1,2,3,4]
Run Code Online (Sandbox Code Playgroud)

解构清单:

?> let first:second:rest = [1, 2, 3, 4]
?> first
1
?> second
2
?> rest
[3, 4]
Run Code Online (Sandbox Code Playgroud)

这同样适用于Haskell中的许多数据构造函数.您可以使用Just构造Maybe值.

?> let name = Just "John"
?> :type name
name :: Maybe [Char]
Run Code Online (Sandbox Code Playgroud)

但是,您也可以使用它来分解Maybe值.

?> let Just x = name
?> x
"John"
Run Code Online (Sandbox Code Playgroud)


mhw*_*bat 9

这里发生了两件不同的事情.您的第一个示例使用(:)运算符从元素1和列表创建新列表[2,3].

1:[2,3]
Run Code Online (Sandbox Code Playgroud)

您的第二个示例使用模式匹配.表达方式...

myInt (x:xs) = ...
Run Code Online (Sandbox Code Playgroud)

...本质上说"如果参数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]"
Run Code Online (Sandbox Code Playgroud)

请注意,这仅在输入列表包含至少一个元素时才有效.

?> myInt []
"*** Exception: <interactive>:9:34-127: Non-exhaustive patterns in function myInt
Run Code Online (Sandbox Code Playgroud)

但是,我们可以处理输入列表为空的情况,如下所示:

?> 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"
Run Code Online (Sandbox Code Playgroud)