Why is `($ 4) (> 3)` equivalent to `4 > 3`?

后端 未结 3 1895
暖寄归人
暖寄归人 2021-01-04 18:58

I noticed as I was playing around with Haskell today that it is possible to do something like

($ 4) (> 3)

which yields True

相关标签:
3条回答
  • 2021-01-04 19:21

    You can partially apply an infix operator from either side. For commutative operators such as +, it doesn't matter if you say (+ 1) or (1 +), but for example for division you can supply either the dividend (5 /) or the divisor (/ 5).

    The function application operator takes a function as the left-hand operand and a parameter as the right-hand operand (f $ x), so you can partially apply it either with a function (f $) or with a parameter ($ x). So given

    ($ 4) (> 3)
    

    You first partially apply the $-operator with the parameter 4 and supply it with the function (> 3). So what this essentially becomes is

    (> 3) $ 4
    

    Which is the same as (4 > 3).

    0 讨论(0)
  • 2021-01-04 19:21

    ($ 4) is the function that takes a function and applies 4 to it.

    (> 3) is the function that takes a number and checks if it is greater than 3.

    So by giving the latter function to the former, you are essentially applying 4 to the function that checks if its input is greater than 3, and thus you get True.

    0 讨论(0)
  • 2021-01-04 19:28

    ($ 4) is what's called a section. It's a way of partially applying an infix operator, but providing the right-hand side instead of the left. It's exactly equivalent to (flip ($) 4).

    Similarly, (> 3) is a section.

    ($ 4) (> 3)
    

    can be rewritten as

    (flip ($) 4) (> 3)
    

    which is the same as

    flip ($) 4 (> 3)
    

    which is the same as

    (> 3) $ 4
    

    And at this point, it should be clear that this boils down to (4 > 3).

    0 讨论(0)
提交回复
热议问题