What exactly is being calculated in which order if i run this code in Haskell?

26 views Asked by At

I came along this piece of coding on this website:

Input: foldr (/) 2 [8,12,24,4]

Output: 8.0

How is this Output being calculated ?

is it 8/(12/(24/(4/2))) = 8.0 ?

1

There are 1 answers

0
5ar On

Yes.

Oh, Stack Overflow doesn't allow short answers. Ok then, a short explanation is in order (although I think you understand it already).

 

foldr is defined as:

foldr :: (a -> b -> b) -> b -> [a] -> b

In simple and more descriptive terms:

foldr :: function_to_apply -> accumulator_start_value -> list -> accumulator_end_value

where function_to_apply is applied on each element of the list from right to left something like this:

next_accumulator_value = function_to_apply current_element current_accumulator_value

Or in case of an infix function (such as the / operator):

next_accumulator_value = current_element `function_to_apply` current_accumulator_value

Note that (/) in your expression is just short for:

(\current_element current_accumulator_value -> current_element / current_accumulator_value)

 

Therefore, your example is calculated like this:

foldr (/) 2 [8,12,24,4]  -- ( 4 2 -> 4/2 )
foldr (/) (4/2) [8,12,24]  -- ( 24 (4/2) -> 24/(4/2) )
foldr (/) (24/(4/2)) [8,12]  -- ( 12 (24/(4/2)) -> 12/(24/(4/2)) )
foldr (/) (12/(24/(4/2))) [8]  -- ( 8 (12/(24/(4/2))) -> 8/(12/(24/(4/2))) )
foldr (/) (8/(12/(24/(4/2)))) []  -- nothing to apply to any more, the accumulated expression can now be evaluated

Which is exactly what you described.