Currying subtraction

后端 未结 4 1065
礼貌的吻别
礼貌的吻别 2020-11-27 20:17

If we want to map a function that increases every element of a range by 1, we could write

map (\\x -> x + 1) [1..5]

but I guess most peo

相关标签:
4条回答
  • 2020-11-27 20:22

    I don't like subtract because it's confusingly backwards. I'd suggest

    minus :: Num n => n -> n -> n
    minus = (-)
    infixl 6 `minus`
    

    Then you can write

    map (`minus` 1) [1..5]
    
    0 讨论(0)
  • 2020-11-27 20:39

    I think map (\x -> x - 1) [1..5] transmits the programmer's intention better, since there's no doubt about what is being subtracted from what. I also find your first solution, map (+(-1)) [1..5], easy to read too.

    0 讨论(0)
  • 2020-11-27 20:43

    You can use the subtract function instead of - if you want to right-section subtraction:

    map (subtract 1) [1..5]
    
    0 讨论(0)
  • 2020-11-27 20:45

    Since - is both the infix subtract and the prefix negate, you can't use the (*x) (where * is an infix operator and x a value) syntax for -. Luckily Prelude comes with negate and subtract, which is \x -> -x and \x y -> y-x respectively, so that you may use those where you need to differentiate between the two.

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