我正在尝试编写一个返回整数绝对值的函数...
abs :: Int -> Int
abs n | n >= 0 = n
| otherwise = -n
myabs :: Int -> Int
myabs n = if n >= 0 then n else -n
它们都适用于正整数但不适用于负整数。 知道为什么吗?
答案 0 :(得分:11)
它们似乎都运行得很好:
Main> myabs 1 1 Main> myabs (-1) 1 Main> abs 1 1 Main> abs (-1) 1
答案 1 :(得分:6)
啊!我不知道你必须在......中加入括号。
myabs (-1)
有人通过了傻瓜帽。
dohhh
答案 2 :(得分:5)
是的,您通常需要使用负值括号来消除运算符优先级的歧义。有关详细信息,请参阅Real World Haskell chapter 1。