Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does OCaml have fusion laws

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

  1. Is OCaml the same that it prefer modular programs like shown above in Haskell?
  2. Does OCaml also have fusion laws?
  3. If I want to be an OCaml professional, should I really care or learn from Haskell's fusion laws?
like image 631
Jackson Tale Avatar asked Dec 26 '22 15:12

Jackson Tale


1 Answers

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.

like image 123
svenningsson Avatar answered Jan 08 '23 15:01

svenningsson