2016 is coming....
Monadic Design

Functional Programming
Quem sou eu?
•   Rodrigo Vidal
•   MVP de F#
•   Rio de Janeiro
•   Computação Científica / Engenharia
Agenda




   Composição
Linguagens
12



                      C#, VB,
             10
                       Java         LINQ       F#       Nirvana


              8




Usefulness    6                                                        C#
                                                                       Nirvana
                                                                       Haskell
              4
                                                                       LINQ


              2
                                                        Haskell

              0
                  0      2      4          6        8      10     12


                                       Safety
Programação Funcional
•   Imutabilidade
•   First-class Functions
•   Lazy
•   Pattern Matching
•   Composição
Transparência Referencial

void Multiplicar(Matriz m1, Matriz m2)
{
     ....
}
Efeitos Colaterais
String Nome(Person p)
{
      C.WriteLine(“Isto é um efeito colateral!”);
      return p.Nome;
}
Aplicação Parcial
• Aplicação parcial envolve passar menos
  argumentos para uma função que recebe
  múltiplos argumentos

add :: Int -> Int -> Int
add x y = x + y
addOne = add 1
Currying
Currying é o processo de transformar uma função
que recebe multiplos argumentos para uma função
que recebe somente um argumento e retorna uma
outra função se algum paramêtro ainda for
necessário.

f :: a -> b -> c
É a forma ”curried” de
g :: (a, b) -> c
Funções de Alta Ordem
•   Filter          •   First
•   Map             •   Last
•   Length          •   Zip
•   All             •   Take
•   Any             •   TakeWhile
•   Max
•   Min
Composição de Funções

f(g(x))        g(x)




g >> f
f.g                   f(x)
A Essência do LINQ
O tipo Option
Destilando o LINQ
• IEnumerator<T> == Func<Option<T>>

• () –> Option<T>

• IEnumerable<T> == Func<Func<Option<T>>>

• () –> (() –> Option<T>)
Empty<T>()
Return<T>()
static Func<Func<Option<T>>> Return<T> (T value)
{
return () => {
        int i = 0;
        return () =>
                i++ == 0
                ? (Option<T>)new Option<T>.Some(value)
                : (Option<T>)new Option<T>.None();
        };
 }
Select<T>
Where<T>
SelectMany<T>
IE<R> SelectMany<T, R>(this IE<T> source,
                                  Func<T, IE<R>> f)
{
 foreach (var item in source)
      foreach (var result in f(item))
           yield return result;
}
LINQ somente em IEnumerable?
Functors
class Functor f where
       fmap :: (a -> b) -> f a -> f b

instance Functor Maybe where
  fmap f (Just x) = Just (f x)
  fmap f (Nothing ) = Nothing

fmap (*2) [1..3]
> [2,4,6]

fmap (*2) Just 5
> Just 10
Funções como Functors
fmap :: (a -> b) -> ((->) r a) -> ((->) r b)

fmap :: (a -> b) -> (r -> a) -> (r -> b)
Applicative Functors
class (Functor f) => Applicative f where
      pure :: a -> f a
      (<*>) :: f (a -> b) -> f a -> f b

let a = fmap (*) [1,2,3,4]
a :: [Integer -> Integer]
Maybe Applicative Functor
instance Applicative Maybe Where
  pure = Just
  Nothing <*> _ = Nothing
  (Just f) <*> something = fmap f something



  pure (+) <*> Just 3 <*> Just 5
  > Just 8
Monoids
class Monoid m where
      mempty :: m
      mappend :: m -> m -> m
      mconcat :: [m] -> m
      mconcat = foldr mappend mempty
Monoids Pattern
• 1+1
• 2*2
• [1,2,3] ++ [4,5,6]
instance Monoid Any where
  mempty = Any False
  Any x `mappend` Any y = Any (x || y)

getAny $ Any True `mappend` Any False
> True

getAny $ Any True `mappend` mempty
> True
instance Monoid All where
  mempty = All True
  All x `mappend` All y = All (x && y)

getAll $ mempty `mappend` All True
> True

getAll $ mempty `mappend` All False
> True
Monads
Monads
class Monad m where
      return :: a -> M a
      bind :: M a -> ( a -> M b) -> M b
List Monad
Maybe Monad
IO Monad
Async Monad
LINQ – Dualidade - Rx
Reactive Extensions
• IObserver<T> == Action<Option<T>>

• Option<T> -> ()

• IObservable<T> == Action<Action<T>>

• (Option<T> -> ()) -> ()
                        • IEnumerator<T> == Func<Option<T>>

                     • () –> Option<T>

                     • IEnumerable<T> == Func<Func<Option<T>>>

                     • () –> (() –> Option<T>)
Notas Finais
• Aprenda Matemática
• Aprenda Algoritmos
• Aprenda uma Linguagem Funcional (F# :P)

• .NET Architects Rio de Janeiro
• DojoRio
• Hora Extra


• @rodrigovidal
• rodrigovidal777@gmail.com
• www.rodrigovidal.net

Monadic Design