Author | Message |
---|---|
tvo54
Posts: 7
|
Posted 18:08 Mar 03, 2019 |
Hi, I don't quite understanding doubleAndSum. Could any of you haskell experts help? For example, what does (False, 0) do at the end of foldr?
Thanks! |
mkuko
Posts: 13
|
Posted 18:38 Mar 03, 2019 |
Hi Tam, Foldr takes 3 arguments (the function to fold on) (the initial value) (the list to fold) In this situation the the arguments are as follows: the function to fold on = (\i (atEvnPos, acc) -> (not atEvnPos, nextVal atEvnPos i + acc) the initial value = (False, 0) the list to fold = the list passed into doubleAndSum (this is part of the point free notation) The function to fold on works with a tuple in this situation it looks like a tuple of a (Bool, Int) The Bool is used to check if we are on a digit that should be doubled or not, so if its true we know to double it and do the fancy math we see in nextVal The Int is an accumulated value, its the sum we want at the end of the doubleAndSum and that value is added up with the return of nextVal. So every iteration through we are flipping the Bool so we know we are on a digit that should be doubled when we pass that into nextVal Since this is a foldr we are starting from the right of the list and we want to double every other value so we start with (False, 0) because the right most digit doesn't need to be doubled and the 0 is the start of the accumulator. Hope this helped.
|
jpatel77
Posts: 44
|
Posted 18:40 Mar 03, 2019 |
(False, 0) keeps track of the accumulated total and the current position e.g. even, odd. the fn part of foldr i.e.
performs:
Since the first index is odd, value of foldr takes this fn along with the initial value Finally, it extracts the 2nd element of the final value of Last edited by jpatel77 at
19:35 Mar 03, 2019.
|
tvo54
Posts: 7
|
Posted 19:32 Mar 03, 2019 |
AAAAAAAAAAAAHHHHHHHHHHH. This was really helpful. Thanks guys! |