Haskell Higher Order Functions

Filter

filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter p (x:xs)
| p x = x : filter p xs
| otherwise = filter p xs
Prelude> filter (==3) [1,2,3]
[3]
Prelude> filter (==3) [1,2,33]
[]

Map

map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
Prelude> map (*5) [1,2,3]
[5,10,15]

Lambda

Prelude> map (\x->x*5) [1,2,3]
[5,10,15]
Prelude> (\x->x [11,2,3,4]) head
11

Foldl

Prelude> :t foldl
foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b
Prelude> foldl (+) 4 [1,2,3]
10
Prelude> foldl (+) 3 (Just 5)
8

Foldr

Prelude> :t foldr
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
  1. The accumulator is the second argument to the function argument.
  2. Folding is done starting from the last element if (t a) (makes more sense when (t a) is a list).
Prelude> foldr (+) 4 [1,2,3]
10
Prelude> foldr (+) 3 (Just 5)
8
Prelude> foldl (-) 0 [1,2,3,4,5]
-15
Prelude> foldr (-) 0 [1,2,3,4,5]
3
  1. foldl : (((((0-1)-2)-3)-4)-5)
  2. foldr : (1-(2-(3-(4-(5-0)))))

($)

($) :: (a -> b) -> a -> b
f $ x = f x
Prelude> (+) 100 $ foldl (+) 2 $ map (*5) [1,2,3,4,5]
177
Prelude> (+) 100 ( foldl (+) 2 ( map (*5) [1,2,3,4,5]))
177

(.)

(.) :: (b -> c) -> (a -> b) -> a -> c
f . g = \x -> f (g x)
Prelude> let addmul = ((+3).(*2))
Prelude> addmul 4
11
Prelude> let plus3 = (+3)
Prelude> let plus2 = (+2)
Prelude> let plus1 = (+1)
Prelude> (plus1 . plus2 . plus3) 4
10

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What Our Software Development Process Looks Like

Approach to internal courses in IT companies

Swift Solutions: Decorator Pattern

Help — HackTheBox Writeup

Working around process bandwidth bottlenecks

Code Smell 16 — Ripple Effect

Numerical Programming in C with Examples

How to Deploy a CentOS Linux VM in Azure using Terraform

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Priyanka Mondal

Priyanka Mondal

More from Medium

Croodles

How Holo-NFT Blurs the Line Between Traditional and Contemporary Art

How Likely is World War III?

npx and npm