Prefix form of unary operator in Haskell

前端 未结 4 678
野趣味
野趣味 2020-11-30 15:08

In GHCi:

  1. Prelude> (+3) 2
    5
  2. Prelude> (*3) 2
    6
  3. Prelude> (/3) 2
    0.6666666666666666
  4. Prelu
相关标签:
4条回答
  • 2020-11-30 15:39

    Haskell's grammar doesn't allow you to use - like that. Use the subtract function instead:

    (subtract 3) 2
    0 讨论(0)
  • 2020-11-30 15:40

    If you're intent on keeping your original shape, you can always add the negative:

    (+ -3)
    

    It ain't pretty, but it fits your pattern a little bit more.

    0 讨论(0)
  • 2020-11-30 15:42

    As a footnote to grddev's answer, here's the relevant paragraph from the Haskell 98 Report:

    The special form -e denotes prefix negation, the only prefix operator in Haskell, and is syntax for negate (e). The binary - operator does not necessarily refer to the definition of - in the Prelude; it may be rebound by the module system. However, unary - will always refer to the negate function defined in the Prelude. There is no link between the local meaning of the - operator and unary negation.

    This is something that frustrated me when I first came across it: I couldn't understand why the operators behaved so differently in this context when :info (+) and :info (-) looked basically identical.

    You could use subtract, as grddev suggests, or you could just define a new infix operator:

    Prelude> let (#) = (-)
    Prelude> (# 3) 2
    -1
    

    subtract has the advantage of being familiar to other people who might read your code.

    0 讨论(0)
  • 2020-11-30 15:49

    You can do

    (-) 3 2
    

    but that will give you 1. To have -1, you need to bind the 3 to the second argument of -, which you can do using

    flip (-) 3 2
    
    0 讨论(0)
提交回复
热议问题