简体   繁体   English

Haskell列表中的列表

[英]Haskell Lists in List

I'm very new on Haskell, and I'm trying the following: To obtain [1,2,3] from [[1,2,3],[4,5,6]] ? 我是Haskell的新手,我正在尝试以下操作:从[[1,2,3],[4,5,6]]获得[1,2,3] [[1,2,3],[4,5,6]]吗?

example :: [[a]] -> [a]
example [] = []
example [x:xs] = [x]

This example is returning [1] when input is [[1,2,3]] and if I add an other element in the main List, like [[1,2,3],[3,4,5]] then I have a Non-exhaustive pattern function. 当输入为[[1,2,3]]且如果我在主列表中添加另一个元素,例如[[1,2,3],[3,4,5]]时,此示例返回[1]我有一个非穷尽模式功能。

You are quite close. 你很亲密 In fact what you here want is some sort of "safe" head. 实际上,您在这里想要的是某种“安全”的头。

A list [a] has two constructors: 列表[a]具有两个构造函数:

  1. the empty list [] , you cover this in the first case; 空列表[] ,您将在第一种情况下解决此问题; and
  2. the "cons" (x:xs) . “ cons” (x:xs)

It looks like you cover that in the second case, but in fact you do not: you put the pattern within square brackets. 在第二种情况下,您似乎已将其覆盖,但实际上您没有:将图案放在括号中。 As a result, Haskell interprets your pattern as [(x:xs)] . 结果,Haskell将您的模式解释为[(x:xs)] So it thinks you match a singleton list (a list with one element), and that x is the head of the sublist, and xs the tail of the sublist. 因此,它认为您匹配一个单例列表(一个具有一个元素的列表),并且x是子列表的开头,而xs是子列表的结尾。

In fact you want to cover (x:xs) . 实际上,您想覆盖(x:xs) If we use this pattern, there is another problem: x is the head of the list, so it has type [a] . 如果我们使用此模式,则还有另一个问题: x是列表的开头,因此类型为[a] Therefore we should return x , not [x] , since in the latter case, we would wrap the sublist back in a list. 因此,我们应该返回x而不是[x] ,因为在后一种情况下,我们会将子列表包装回列表中。

So a correct function is: 因此正确的功能是:

example :: [[a]] -> [a]
example [] = []
example (x:_) = x  -- round brackets, x instead of [x]

Note that since we are not interested in the tail here, we use an underscore _ . 请注意,由于我们对这里的尾部不感兴趣,因此我们使用下划线_ If you compile with all warnings ( -Wall , or more specific -Wunused-matches ) Haskell will otherwise complain about the fact that you declare a variable that you do not use. 如果您编译所有警告( -Wall或更具体的-Wunused-matches ),则Haskell会抱怨您声明了一个不使用的变量。

Generalizing to a safeHead function 泛化为safeHead函数

We can generalize this to some sort of generic safeHead :: b -> (a -> b) -> [a] -> b function: 我们可以将其概括为某种通用的safeHead :: b -> (a -> b) -> [a] -> b函数:

safeHead :: b -> (a -> b) -> [a] -> b
safeHead d _ [] = d
safeHead _ f (x:_) = f x

Here we thus pass three arguments to safeHead : a value (of type b ) we should return in case the list is empty; 因此,这里我们将三个参数传递给safeHead :一个值(类型b ),如果列表为空,则应返回该值; a function to post-process the head (type a -> b ), and the list to process . 一个对头部进行后处理的函数(键入a -> b )以及要process的列表。 In that case the example is equivalent to: 在这种情况下,该example等效于:

example :: [[a]] -> [a]
example = safeHead [] id

But we can also return a Maybe [a] here: 但是我们也可以在这里返回Maybe [a]

example2 :: [a] -> Maybe a
example2 = safeHead Nothing Just

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM