

Functor and Monad in Swift - JSoto
http://www.javiersoto.me/post/106875422394

======
spion
This is a great article. It captures the essence of functors and monads in
programming really well without the usual nonsensical analogies from other
similar tutorials.

There are just a few tiny pieces missing from the puzzle: the functor and
monad laws. They're pretty straight-forward - one would think they're common
sense.

For functor, there is the mapping with identity law:

functor.map({ $0 }) == functor

which says that mapping the identity function over a functor results with a
value equal to the one we started with

and the law for compositionality

functor.map({ f2(f1($0)) }) == functor.map(f1).map(f2)

which states that mapping a composite function yields the same result as
mapping the first function then mapping the second function onto the result of
the first map.

For monad, there are 3 additional laws (left identity, right identity and
associativity).

~~~
JSoto
Thanks!

I think that would make for another interesting article. I purposely ignored
those details to make sure I kept my article more practical and less academic
:) I also didn't mention the unit function of Monads (is that equivalent to
one of the laws that you refer to?)

------
hardwaresofton
This is an excellent article, I think it explains the monad pretty simply,
starting from an understanding of functors.

For those that are struggling with understanding (or feeling like you
understand) monads, here are some articles like this one that I found very
useful (note that the links are for haskell, but obviously, monads are a
generally applicable concept).

A visual explanation of monads:

[http://adit.io/posts/2013-04-17-functors,_applicatives,_and_...](http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html)

The chapters on Functors, Applicatives, and Monoids that leads up to the
chapter on monads (read the functors, applicatives, and monoids chapter first
THEN the monad chatper and things will start to make sense):

[http://learnyouahaskell.com/functors-applicative-functors-
an...](http://learnyouahaskell.com/functors-applicative-functors-and-monoids)

~~~
bvanslyke
Personally it clicked for me after reading "You Could Have Invented Monads"[0]
and LYAH (in order as you suggest).

[0] [http://blog.sigfpe.com/2006/08/you-could-have-invented-
monad...](http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-
and.html)

------
CookWithMe
Nice article, well done!

Minor question/comment regarding the implementation of Result.map: Why do you
create a new Result in the error case? Result is immutable (or am I missing
something specific to Swift here?), so the old and new Result are the same and
stay that way.

I'm not familiar with the internals of Swift, but e.g. in Scala, there is only
one "None". If you call map or flatMap on it, the same None will always be
returned.

~~~
DanWaterworth
I'm not familiar with swift, but in Haskell, you can't write the following:

    
    
        flatMap :: Either e a -> (a -> Either e b) -> Either e b
        flatMap x f =
          case x of
            Left _ -> x
            Right x' -> f x'
    

In the case expression, you have to write `Left err -> Left err`, because `x`
here has the type `Either e a`, but `Either e b` is expected.

~~~
JSoto
Yeah, this is correct. This would be wrong:

    
    
        func map<U>(f: T -> U) -> Result<U> {
            switch self {
            case let .Value(value):
                return Result<U>.Value(Box(f(value.unbox)))
            case let .Error(error):
                // self is Result<T>, but the return type must be Result<U>
                return self
            }
        }

------
saosebastiao
Can someone help me bridge the gap between this understanding of the
definition of functor and the ocaml version?

In ocaml, a functor is a module that takes another module as a parameter. In
this, a functor is a type that implements the map method. Is there something
I'm missing that explains how both of them are functors?

~~~
_Robbie
The simple explanation is that the word functor is being used for two
different concepts.

I found this question on Stackoverflow.

[http://stackoverflow.com/questions/16353066/how-are-
functors...](http://stackoverflow.com/questions/16353066/how-are-functors-in-
haskell-and-ocaml-similar)

------
IsTom
Is there return type polymorphism in Swift? Without it monad-generic
operations are limited.

~~~
josephlord
Yes.

    
    
      func f()->Bool {
        return true
      }
      func f()->Int {
        return 5
      }
    
      let i:Int = f()
      let b:Bool = f()
    
      println(i) // Prints 5
      println(b) // Prints true
      
      // This would be compile error as ambiguous
      //println(f())

------
dons
I'm not sure I could implement monadic APIs in another language based on this
post.

------
melling
For more articles on functional programming and Swift:

[http://www.h4labs.com/dev/ios/swift.html?q=functional&age=10...](http://www.h4labs.com/dev/ios/swift.html?q=functional&age=10000)

