def compute2(maybeFoo: Option[Foo]): Option[Int] =
maybeFoo.flatMap { foo =>
foo.bar.flatMap { bar =>
bar.baz.map { baz =>
baz.compute
}
}
}
然后将其翻译成为理解:
def compute2(maybeFoo: Option[Foo]): Option[Int] =
for {
foo <- maybeFoo
bar <- foo.bar
baz <- bar.baz
} yield baz.compute
我的问题是如何将此地图/ flatMap转换为Clojure中的理解?
假设:
mapcat
)代表这个而不是algo.monads
/ fluokitten
库。但如果这是最好的方式(我开放学习),那就用它。 答案 0 :(得分:2)
你可能不会在Clojure中使用Option
,但如果对象在内部集合中,那么这样的东西应该可以工作:
(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)))
;=> '()