Haskell foldr calculation steps

Does anyone know the steps for using the haskell 'foldr' function?

GHCI Command Window:

foldr (\x y -> 2*x + y) 4 [5,6,7] 

Result after evaluation:

40

Steps on this

Prelude> foldr (\x y -> 2*x + y) 4 [5,6,7] 
6 * 2 + (7 * 2 + 4)
12 + 18 = 30
5 * 2 + 30 = 40 v
+3
source share
3 answers

One definition of foldr:

foldr            :: (a -> b -> b) -> b -> [a] -> b
foldr f acc []     = acc
foldr f acc (x:xs) = f x (foldr f acc xs)

Haskell wikibook has a nice schedule in foldr (and in other warehouses too):

  :                         f
 / \                       / \
a   :       foldr f acc   a   f
   / \    ------------->     / \
  b   :                     b   f
     / \                       / \
    c  []                     c   acc

those. a : b : c : [](it's simple [a, b, c]) becomes f a (f b (f c acc))(again, taken from wikibook).

So your example is evaluated as let f = (\x y -> 2*x + y) in f 5 (f 6 (f 7 4))(let-binding for brevity only).

+7
source

You can easily visualize this for yourself:

import Text.Printf

showOp f = f (printf "(%s op %s)") "0" ["1","2","3"]

then

Main> showOp foldr
"(1 op (2 op (3 op 0)))"
Main> showOp foldl
"(((0 op 1) op 2) op 3)"
Main> showOp scanl
["0","(0 op 1)","((0 op 1) op 2)","(((0 op 1) op 2) op 3)"]
0
source

[ delnan, ...]

, "" lambdabot #haskell irc (, http://webchat.freenode.net/). , , .

    Yoon: > foldr (\x y -> 2*x + y) o [a,b,c,d]
lamdabot: 2 * a + (2 * b + (2 * c + (2 * d + o)))

, , , ,

     Yoon: > reverse (scanr (\x y -> 2*x + y) o [a,b,c,d])
lambdabot: [o,2 * d + o,2 * c + (2 * d + o),2 * b + (2 * c + (2 * d + o)),2 * a + (2 * b + (2 * c + (2 * d + o)))

I remember that captures some good lessons, playing with the foldr, foldl, scanr, scanland this smart device.

0
source

Source: https://habr.com/ru/post/1760701/


All Articles