Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

By analogy to fix:

fix f --> f (fix f)

That is, to compute the fixed point of some function f, we give f access to the fixed point (i.e. fix f) in order to compute the fixed point.

Consider f is strict, and that we try to run this:

    fix f --> f (fix f)
          --> f (f (fix f))
          --> f (f (f (...)))
Why? Because if f is strict it has to evaluate its argument before evaluating the body.

On the other hand, if f is non-strict, we can evaluate its body without evaluating its argument first.

mfix generalizes fix to monadic functions. When we have monadic functions, we're usually dealing with side-effectful computation, so we want to make sure that we only force the monadic action f once, so that the side effects only run once.

---

Another question to ask is "what is fix even useful for"? fix is how we introduce general recursion into a language. For example, the lambda calculus has fix, except it's called the Y combinator. Compare:

    Y f   --> f (Y f)
    fix f --> f (fix f)
The lambda calculus is Turing complete because it has this general recursion.

fix is often used in smaller toy languages to also make them Turing complete, because this form of recursion is straightforward.

While Haskell has recursive function definitions, fix (and mfix more generally) are sometimes useful in their own right.



I think you answered the wrong "why".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: