Why is the use of Maybe/Option not so pervasive in Clojure?

后端 未结 7 2180
长发绾君心
长发绾君心 2020-12-24 01:36

Why does Clojure, despite such an emphasis on functional paradigm, not use the Maybe/ Option monad to represent optional values? The use of O

7条回答
  •  清歌不尽
    2020-12-24 01:56

    In Clojure, nil punning provides most of the functionality that Scala & Haskell get from Option & Maybe.

    **Scala**                **Clojure**
    Some(1) map (2+_)        (if-let [a 1] (+ 2 a))
    
    Some(1) match {          (if-let [a 1]
      case Some(x) => 2+x      (+ 2 a)
      case None    => 4        4)
    }
    

    Scala's Option & Haskell's Maybe are both instances of Applicative. This means that you can use values of these types in comprehensions. For example, Scala supports:

    for { a <- Some(1)
          b <- Some(2)
    } yield a + b
    

    Clojure's for macro provides comprehensions over seq. Unlike monadic comprehensions, this implementation allows mixing instance types.

    Though Clojure's for can't be used for composing functions over multiple possible nil values, it's functionality that's trivial to implement.

    (defn appun [f & ms]
      (when (every? some? ms)
        (apply f ms)))
    

    And calling it:

    (appun + 1 2 3)    #_=> 6
    (appun + 1 2 nil)  #_=> nil
    

提交回复
热议问题