Jhon Duck
Jhon Duck

Reputation: 377

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

The code is

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

The trace is

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

Is there a solution without alter the list?

Upvotes: 2

Views: 100

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476719

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.

Upvotes: 6

Related Questions