Recently I am reading some functional programming books involving Haskell.
It seems Haskell quite fancies “modular programs”, for example,
f :: (Integer,Integer) -> Integer
f = sum . map sq . filter . odd . between
even though the same function can be written like
f' (m, n) = go m
where go m | m > n = 0
| otherwise = go (m + 1) + if odd m then sq m else 0
Also “fusion laws” are quite popular and used (http://www.cs.ox.ac.uk/ralf.hinze/publications/IFL10.pdf)
I am not an OCaml expert, but I would use fold_left
or fold_right
if possible and easy and efficient (for example, anyway I have to scan the whole list and won't stop in the middle).
However, at most of the time, I will write explicit recursive code using “pattern matching”.
Also I read quite some OCaml projects in github and explicit recursive seems are very usual.
In addition, I never heard of fusion law for OCaml.
My questions are
Fusion is not as easy to implement in OCaml as it is in Haskell due to side-effects. If you were to go ahead and fuse functions in OCaml in the same way that GHC fuses them, then you would get very unpredictable results, and side-effects happening in a different order than how you wrote the program. So, no, OCaml doesn't have "fusion laws", as you put it. That doesn't mean it's impossible to do fusion in OCaml, you just have to work harder.
Compilers for imperative languages sometimes implement loop-fusion, which has a similar effect to fusion in Haskell. OCaml could benefit from loop-fusion but it's a much more involved optimization to implement.
Fusion is a very good example of one of the benefits of not having side-effects in Haskell. It makes certain optimizations much easier to implement and they can give much stronger guarantees about when the optimization trigger.
I don't think you need to know that much about fusion in order to be an effective OCaml programmer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With