Search code examples
listhaskellfold

Exponentiate all elements of a list without alter the list


The list is

[2, 3, 4]

and I want exponentiate each result. So, it would be:

(2 ^ 3) ^ 4 = 4096

My solution is

  • use foldl
  • set manually the first element of the list as the base case
  • set manually the base case as the first element of the list

The code is

foldl (^) 2 [1, 3, 4]

The trace is

((2 ^ 1) ^ 3) ^ 4 = 4096

Is there a solution without alter the list?


Solution

  • Yes, in case the list is guaranteed to have a first element, we can use foldl1 :: (a -> a -> a) -> [a] -> a which uses the first element of the list as initial accumulator. So we can use:

    foldl1 (^) [2, 3, 4]

    This of course produces the same result:

    Prelude> foldl1 (^) [2,3,4]
    4096
    

    Note that in case you use an empty list the above function will error. So you will need to handle that case - if that is a possibility - by some extra logic.