Skip to content

Instantly share code, notes, and snippets.

@RyanKung
Last active September 10, 2018 13:48
Show Gist options
  • Save RyanKung/f5bd54c9398a5a4cd67a7eedbf289b9b to your computer and use it in GitHub Desktop.
Save RyanKung/f5bd54c9398a5a4cd67a7eedbf289b9b to your computer and use it in GitHub Desktop.
Functor, Applicative, Monad, Semigroup, Monoid in Haskell and Rust

Functor

class Functor f where
    fmap :: (a -> b) -> f a -> f b
trait Functor<T> {
    fn fmap<F, U>(Self<T>, f: F) -> Self<U>
         where F: Fn(T) -> U;
}

Applicative

class (Functor f) => Applicative f where
    pure :: a -> f a
    (<*>) :: f (a -> b) -> f a -> f b
trait Applicative<T>: Functor<T> {
   fn pure(t: T) -> Self<T>;
   fn chain<F, U>(Self<T>, f: F) -> Self<U>
        where F: Self<Fn(T) -> U>;
}

Monad

class Applicative m => Monad m where
  return :: a -> m a
  (>>=) :: m a -> (a -> m b) -> m b
trait Monad<T>: Applicative<T> {
    fn bind<F, U>(Self<T>, F) -> Self<U>
        where F: Fn(T) -> Self<U>;
}

SemiGroup

class Semigroup a where
    (<>) :: a -> a -> a infixr 6
trait SemiGroup<T> {
    fn append(a: T, b: T): T
}

Monoid

class Semigroup m => Monoid m where
    mempty :: m
trait Monoid<T>: Semigroup<T> {
    const zero: T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment