7 ms·
The OCaml version (for 2 lists) is almost as good as clojure List.map2 ( + ) a b;; However, for 3 or more lists, Clojure definitely wins (since there's no
by krat0sprakhar 11y ago
The OCaml version (for 2 lists) is almost as good as clojure
List.map2 ( + ) a b;;
However, for 3 or more lists, Clojure definitely wins (since there's no variadic equivalent of map in OCaml) -
let x = List.map2 ( + ) a b in List.map2 ( + ) x c;;
Which got me wondering, is there a particular reason why only a `map2` exists in OCaml?
- mbel 11y agoNot surprisingly, the sum of two lists is just as nice in Haskell: zipWith (+) a b ... and things get a little bit hairy with three lists: zipWith3 (\x y z -> x + y + z) a b c ... which is still nice but for four lists we get to the same point as OCaml: let a' = zipWith (+) a b in zipWith3 (\x y z -> x + y + z) a' c d I guess in both OCaml and Haskell the user is expected to define zipWith4, zipWith5, etc. (or map in OCaml's case) if he fells the need to use them. There is probably a simple and elegant way to get variadic-like behavior in Haskell by folding list of list, or playing with Foldable and Sum, but it's a little bit to early in the morning for me to generalize it.
- eru 11y agoYou can also write: liftA2 (+) or (+) <$> a <*> b if you have the right type-class instance.
- droque 11y agoYou could also go all the way and declare a Num a => Num [a] typeclass, with (+) = zipWith (+).
- eru 11y agoSee https://hackage.haskell.org/package/base-4.8.2.0/docs/Data-List.html#v:zipWith5 https://hackage.haskell.org/package/base-4.8.2.0/docs/Data-L...