introduction to fp with haskell - parmg · introduction to functional programming with haskell...
TRANSCRIPT
IntroductiontoFunctionalProgrammingwithHaskell
MohammedAlRujayiWorks@Wasphi
Twitter,Github:@mohalrej
WhatisFunctionalProgramming?
CC++
Python
C#
RubyPHP
Swift
Perl
Smalltalk
Erlang
Haskell
ML
AdgaElm
F#
Lisp
Ocaml
Imperative(HOW?)
Functional(What?)
FunctionalProgramminghasthefollowing…
• Highorderfunctions,functionsthattakeotherfunctions
• Purefunctions,nosideeffects
• Nomutations
• Recursionnotloops
It’sjustlikeLegos!
Anexample
Thefactorialfunctions
5!=5*4*3*2*1
3!=3*2*1
FactorialinPython…
def factorial(n):result = 1while n >= 1: # loop
result = result * n # mutationprint (result) # side effects n = n – 1 # mutation
return result
FactorialinHaskell…
Factorial 0 = 1Factorial 1 = 1Factorial n = n * Factorial (n-1)
Haskelldemo
We’llcover
• Lists
• Application
• Lambdafunctions
• Maps,folds,filters
• Patternmatching
• Composition
Fibonacciseries
0,1,1,2,3,5,8,13…
Startingwith0,and1
Fib(n)=Fib(n-1)+Fib(n-2)
Fibonacciseries
0,1,1,2,3,5,8,13…
Startingwith0,and1
Fib(n)=Fib(n-1)+Fib(n-2)
Notagooddefinition!
F(5)
F(4)
F(3)
Notagooddefinition!
F(5)
F(4)
F(3)
F(3)
F(2)
F(2)
F(1)
Notagooddefinition!
F(5)
F(4)
F(3)
F(3)
F(2)
F(2)
F(1)
Abetteridea
(x,y)->(x+y,x)
Abetteridea
(x,y)->(x+y,x)
At(0,1):
(0,1)->(1,0)
(1,0)->(1,1)
(1,1)->(2,1)
(2,1)->(3,2)
…
AllstandardfunctionsareimplementedinHaskell!!
map f [] = []map f (x:xs) = (f x) : map f xs
ThecoreofHaskell
Lambdas
fold
map
filteriterate
:
mod
++
Factorial
Fibonacci
Yourprogram
EasiestwaytogetHaskell
• Haskellplatform
https://www.haskell.org/platform/
• Haskellformac
http://haskellformac.com
Appendix:Democodemodule Ksu where
-- First factorial, implemented with recursionfac 0 = 1fac 1 = 1fac n = n * fac(n-1)
-- Composition of two functionsksu_01 = map (\ x-> x^2) . map (\ x -> x^2)
-- Sum implemented in terms of foldsum_01 list = foldl (\ x y -> x + y) 0 list
-- The fib function implemented with recursionfib 0 = 0fib 1 = 1fib n = fib (n-1) + fib (n-2)
-- The fib function implemented in terms of iteratefib_01 n = take n $ iterate (\(x, y) -> (x+y, x)) (0, 1)fib_02 = last . map (\(x, y) -> y) . fib_01
يعطیكم العافیة