Intro to Functional Programming

Preview:

DESCRIPTION

Introduction to functional programming for a local meetup.

Citation preview

FUNCTIONALPROGRAMMING

by Andraž Bajt @edofic

available atslides.com/edofic/functional-programming

WHO AM I?CS student at FRI

developer at Koofr

STaaS provider startup

ENTROPY

HALTING PROBLEM

FIGHTING ENTROPY

OBJECT ORIENTATIONmodel real worldobjects all the way down3 rulesdesign patterns

FUNCTIONS

LAMBDA CALCULUSAlonso Curch 1930sEquivalent to Turing Machine

LAMBDA CALCULUSVery simple

Abstractionλx.y

Applicationf x

Composability!

WHAT IS FP?

WHAT IS FP?Programming with values

Using function to transform values

MY STORY(roughly)

1. C(++)2. C#3. Java4. Python5. Scala6. Haskell

WHY MOVE TO FP LAND?Composability Abstractions

GOT MATH?

EXAMPLESfunction apply(f, x) { <div style="text-align: center;"></div> return f(x); }

apply(function(x){ return x * 2}, 1);

apply = (f,x) => f x

apply((x) => x * 2, 1)

CURRYING apply = (f) => (x) => f x

apply((x) => x * 2)(1)

COMPOSITION compose = (f) => (g) => (x) => f(g(x)) foo = (x) => x + 1 bar = (x) => x * 2 f = compose(foo)(bar)

f(2) # 5

COLLECTIONS people = [ {name: "John", surname: "Doe", age: 35}, {name: "Jane", surname: "Doe", age: 49} ]

people .filter((p) => p.age > 40) .map((p) => p.name + p.surname)

people.reduce(((total, p) => total + p.age), 0) / people.length

HELLO HASKELL WEBmain :: IO ()main = scotty 3000 helloRoutes

helloRoutes :: ScottyM ()helloRoutes = do get "/" $ html "hello there" get "/hello" $ html "Hello world" post "/hello" $ html "Hello postman" get "/hello/:name" $ do name <- param "name" html $ "Hello " mappend name

DSLpostUsersR :: Handler ValuepostUsersR = do Auth.adminOnly user <- requireJsonBody userIdMby <- runDB $ insertUnique user runValidationHandler $ ("username", "User with the supplied username already exists") validate (isJust userIdMby) getUsersUserR $ fromJust userIdMby

BUILDING A DSLdata Command a = Up a | Down a deriving (Eq, Show, Functor)type Sequence = Free Command () up, down :: Sequence -> Sequenceup = Free . Updown = Free . Down

done :: Sequencedone = Pure ()go = ($done) example = do go up go up go down go up

ORIGAMIfsum :: (Num a) => Fold a afsum = Fold (+) 0 id flen :: (Num b) => Fold a bflen = Fold (\s _ -> s + 1) 0 fromInteger favg :: (Fractional a) => Fold a afavg = (/) <$> fsum <*> flen

example = runfold favg [1,2,3]

ORIGAMI IMPLEMENTATIONFor foldable things

data Fold a b = forall x . Fold (x -> a -> x) x (x -> b) instance Functor (Fold a) where f fmap Fold step zero map = Fold step zero (f . map) instance Applicative (Fold a) where pure a = Fold const () (const a) Fold f1 z1 m1 <*> Fold f2 z2 m2 = Fold f z m where f (x1,x2) e = (f1 x1 e, f2 x2 e) z = (z1, z2) m (f, x) = (m1 f) (m2 x) runfold :: (Foldable t) => Fold a b -> t a -> brunfold (Fold f z m) t = m $ foldl' f z t

YOU SHOULD TRY ITLibraries for your language

Learn a new language!

QUESTIONS

Recommended