Question

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.

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.

Was it helpful?

Solution

The binding of x in the list comprehension is hiding the variable x from the pattern. 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. It is all the elements after x1, which is the head. If you want to add x1 to all the elements including itself, you could write

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

or in terms of head

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

OTHER TIPS

Try this:

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

or

addFirstEl [] = []
addFirstEl l@(x:_) = map (+ x) l
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top