simple Haskell functions in point-free style

后端 未结 4 1901
日久生厌
日久生厌 2021-02-08 02:00

I am trying to understand how to convert functions to point-free notation in Haskell. I saw this example, but it is more complicated than what I am looking for. I feel like I un

4条回答
  •  感情败类
    2021-02-08 02:24

    Conversion from lambda-calculus (which Haskell is a variant of) terms to SKI terms (totally pointfree functions, using only const (K), id (I) and <*> (S)) can be done with the following simple rules:

    1. \x -> x translates to id;
    2. \x -> y without x occurring in y translates to const y;
    3. \x -> f g translates to f' <*> g' where
      • f' is a translation of \x -> f and
      • g' is a translation of \x -> g.

    Now you may wonder where does the . come in. There is a special case of the last translation: if f does not have any free occurrences of x, then \x -> f g translates to const f <*> (\x -> g), which is equal to f . (\x -> g).

    Using those rules we can convert your function:

    f = \x -> ((+) 5) (((/) 8) x) = -- by the special-case (.) rule
    ((+) 5) . (\x -> (((/) 8) x)) = -- by eta-reduction ((\x -> f x) = f)
    ((+) 5) . ((/) 8)
    

    Eta-reduction is not necessary to complete the translation, but without it we'd get something messier. For example, the last step would yield ((+) 5) . ((/) 8) . id instead.

提交回复
热议问题