简体   繁体   English

Haskell清单问题

[英]Haskell Trouble with Lists

I'm new to Haskell and I'm trying to write a simple function that takes a list of integers and returns a list such that the first element is added to all the elements of the list. 我是Haskell的新手,正在尝试编写一个简单的函数,该函数采用整数列表并返回列表,以便将第一个元素添加到列表的所有元素中。

This is what I have so far. 到目前为止,这就是我所拥有的。

addFirstEl [] = []
addFirstEl (x:xs) = [x + x | x <- xs]

Unfortunately all this has succeeded in doing is returning a list without the first element and the other elements being doubled. 不幸的是,所有this成功完成的工作是返回一个列表,而第一个元素和其他元素都不加倍。

The binding of x in the list comprehension is hiding the variable x from the pattern. x在列表推导中的绑定正在从模式中隐藏变量x Try this instead: 尝试以下方法:

addFirstEl [] = []
addFirstEl (x1:xs) = [x1 + x2 | x2 <- xs]

Edit 编辑

In response to you comment 回应你的评论

the first element still gets removed from the returned list 第一个元素仍然从返回列表中删除

In (x1:xs) , xs is the remainder or tail of the list. (x1:xs)xs是列表的其余部分或tail It is all the elements after x1 , which is the head . x1之后的所有元素,即head If you want to add x1 to all the elements including itself, you could write 如果要向所有元素(包括自身)添加x1 ,则可以编写

addFirstEl [] = []
addFirstEl (x1:xs) = [x1 + x2 | x2 <- (x1:xs)]

or in terms of head 或就head

addFirstEl [] = []
addFirstEl xs = [head xs + x | x <- xs]

Try this: 尝试这个:

addFirstEl [] = []
addFirstEl l@(x:_) = [x + x1 | x1 <- l ]

or 要么

addFirstEl [] = []
addFirstEl l@(x:_) = map (+ x) l

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

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