Functional Programming

Three Elementary Structures

Mathematics and Abstractions

Mathematical Functions

Rule #1: Functions as values

fn = lambda { |x| x + 2 }puts fn.(2) # = 4
# A function `add` that takes a function `fn`
# and a number `a` as parameters, applies
# `fn` to `a` and adds the result of
# `fn(a)` to `a` again.
def add(fn, a)
fn.(a) + a
end
fn = lambda { |x| x + 2 }
result = add(fn, 2)
puts result # = 2 + 2 + 2 = 6

Rule #2: No Side Effects

# A side effect
File.open("log.txt", "w") { |f| f.write "#{Time.now} - User logged in\\n" }

A Bridge to Side Effects

Atoms

(def x (atom 0))
(swap! x inc)

Agents and Actors

Rule #3: Immutability

x = [1, 2, 3]
y = f(x)
# what is that value of x at this point? x!

Lazy Data Structures

;; (0, 1, 2, 3, 4, ...)
(def integers (range))
;; gets first 10 integers and maps an 
;; increment function on all of them.
(def first-ten-integers (take 10 integers))
(def incremented (map inc first-ten-integers))

Conclusion

References:

--

--

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
Mohammed Amarnah

Mohammed Amarnah

19 Followers

Software Engineer / Machine Learning and Neuroscience Researcher