I came along this piece of coding on this website:
Input: foldr (/) 2 [8,12,24,4] Output: 8.0
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 ?
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
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:
function_to_apply
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.
Yes.
Oh, Stack Overflow doesn't allow short answers. Ok then, a short explanation is in order (although I think you understand it already).
foldris defined as:In simple and more descriptive terms:
where
function_to_applyis applied on each element of the list from right to left something like this:Or in case of an infix function (such as the
/operator):Note that
(/)in your expression is just short for:Therefore, your example is calculated like this:
Which is exactly what you described.