Search code examples
haskellrecursionfold

fold function keep switching var locations


I want to write a function which takes a list of integers and returns a list where every element is negative.

negate :: [Int] -> [Int]
negate xs = foldl (\x xs -> (abs x * (-1)) : xs) [] xs

This function negate all the array objects but also reverse the locations of all variables in the array. What make this function reverse the locations?


Solution

  • foldl does! foldl is a left fold, so it works on your list by starting with its initial state (which you provide as []) and the leftmost element of the list, and calls your function which prepends the negation of that element to the state. Then it takes the next leftmost element and does the same thing. But you're prepending each time, which means that the first element of your input ends up corresponding to the last element of the output, because it was the first to get prepended.

    You might want foldr for this, which is a fold that starts with the rightmost element. Alternatively, using map would be a simpler approach for this particular problem.

    Sample code:

    makeAllNegative = map (negate . abs)