How can I convert this map / flatMap to comprehension for Clojure?

Given this Scala code :

def compute2(maybeFoo: Option[Foo]): Option[Int] =
  maybeFoo.flatMap { foo =>
    foo.bar.flatMap { bar =>
      bar.baz.map { baz =>
        baz.compute
      }
    }
  }  

      

which is then translated into this for understanding:

def compute2(maybeFoo: Option[Foo]): Option[Int] =
  for {
    foo <- maybeFoo
    bar <- foo.bar
    baz <- bar.baz
  } yield baz.compute

      

My question is How to convert this map / flatMap to an understanding for Clojure?

Assumptions:

  • If possible, I would like to use idiomatic Clojure (i.e. mapcat

    ) to represent this, not libraries algo.monads

    / fluokitten

    . But if this is the best way to do it (I'm open to learning) then use that.
+3


source to share


1 answer


You probably wouldn't use it Option

in Clojure, but if objects are inside collections, then something like this should work:



(let [maybe-foo [{:bar [{:baz [(fn [] 42)]}]}]]
  (for [foo maybe-foo
        bar (:bar foo)
        baz (:baz bar)]
    (baz)))
 ;=> '(42)

(let [maybe-foo [{:bar nil}]]
  (for [foo maybe-foo
        bar (:bar foo)
        baz (:baz bar)]
    (baz)))
;=> '()

(let [maybe-foo nil]
  (for [foo maybe-foo
        bar (:bar foo)
        baz (:baz bar)]
    (baz)))
  ;=> '()

      

+2


source







All Articles