Day 6: Haskell

TLDR : Folding

CaptainLazarus
2 min readJan 20, 2022
Day 6 Haskell: Folding
  • foldr/foldl (foldRight and foldLeft)

Folding is a pretty nice operation. Basically, it runs through each element in the list and applies a desired function to it. So what’s the difference between map and foldr? Map treats each element as an individual, and just applies the function to each element only. Folding uses a binary function and recursively applies it to your list using each element as an input.

Better to see it.

foldr :: (a → b → b) → b → [a] → b

If you’re wondering why xs = [1], print out the result.

foldr gives you 1, while foldl gives you -1.

foldr_output = 1–0 (xs-acc)

foldl_ouput = 0–1 (acc-xs)

The accumulator is the last/first element that you’ll apply the function to.

That’s also when you print out the result, foldr ys = -1

(1–2)–0 = -1

foldl ys = (0–2)-1 = -3

This may seem like semantic wrangling for the sake of it, but it is a good idea to keep in mind.

While foldr doesn’t seem great just yet, think about eigenvectors and eigenvalues. Matrix multiplication seems like a great use for this stuff.

Here are some other uses of foldr

even something like length can be represented by folding.

foldr (\x → (+) 1) 0

(or)

foldr (const $ (+) 1) 0

Could probably do a lot more powerful stuff with this, but for now will leave as is.

Note: Map is given as follows

map f = foldr ((:) .f) []

I have no idea what this means. Will read some more and then try to explain.

Just learnt that [X..Y] will print out numbers from X to Y if X≤Y. Otherwise, it returns an empty list.

Note : https://www.youtube.com/watch?v=7sbxVALuuxA

I watched this video and while I understood we could create our own datatypes, I have no clue how to implement them to do whatever. I’ll skip that video and come back later.

--

--

CaptainLazarus

I do stuff. Like stuff about code. And book stuff. And gaming stuff. And stuff about life. And stuff about stuff.