Home Ask Login Register

Developers Planet

Your answer is one click away!

Fraxax February 2016

Trying to understand recursion through a list of integers

I am currently learning how to use recursion in Haskell and I am trying to understand how to go through every element in a list of integers and negate them. So far I can do this but only on the final element of the list so I know that the error lies in the last line. What is the best way to go through every element in a list rather than just the final one?

negation :: [Int] -> [Int]
negation [] = []
negation [n] = [-n]
negation(x:xs) = negation xs


castle-bravo February 2016

Try using the cons operator : to put the negated number at the front of the list.

negation (x:xs) = -x : negation xs

If you do that, you can get rid of the third line.

Luis Casillas February 2016

Well, the best way to write your function is this:

negation :: [Int] -> [Int]
negation xs = map negate xs

{- Example:

>>> map negate [1..5]

Exercise: write your own version of map:

myMap :: (a -> b) -> [a] -> [b]
myMap _ [] = _fillMeIn
myMap f (x:xs) = _fillMeIn

Zacharie 007 February 2016

Simple with map:

  Prelude> let negatList= map (*(-1))


  Prelude> negatList []
  Prelude> negatList [1]

With recursion:

 negation :: [Int] -> [Int]
 negation [] = []
 negation(x:xs) = -x:negation xs

Ratan Senapathy February 2016

As mentioned in an answer before, the best way is to use higher order functions as follows

negation xs = map negate xs

Always use higher order functions whenever possible. It is one of the general Haskell programming guidelines present on wiki.haskell.org and it simplifies your code.

Post Status

Asked in February 2016
Viewed 3,855 times
Voted 6
Answered 4 times


Leave an answer

Quote of the day: live life