Haskell 没有由文字‘;0’;
我的代码:Haskell 没有由文字‘;0’;,haskell,Haskell,我的代码: divisibleBy :: Int -> Int -> Bool divisibleBy x y | mod x y == 0 = True | otherwise = False isEven :: Int -> Bool isEven x | (divisibleBy x 2) == 0 = True | otherwise = False 错误: practical1.hs:30:28: error: • No i
divisibleBy :: Int -> Int -> Bool
divisibleBy x y
| mod x y == 0 = True
| otherwise = False
isEven :: Int -> Bool
isEven x
| (divisibleBy x 2) == 0 = True
| otherwise = False
错误:
practical1.hs:30:28: error:
• No instance for (Num Bool) arising from the literal ‘0’
• In the second argument of ‘(==)’, namely ‘0’
In the expression: (divisibleBy x 2) == 0
In a stmt of a pattern guard for
an equation for ‘isEven’:
(divisibleBy x 2) == 0
|
30 | | (divisibleBy x 2) == 0 = True |
divisibleBy
函数起作用,但isEven
函数不起作用。我做错了什么?错误消息已经说明了这一点。你写道:
isEven :: Int -> Bool
isEven x
| (divisibleBy x 2) == 0 = True
| otherwise = False
但现在它仍然不雅观:我们不必检查条件是否保持返回True
,否则False
,我们只需返回定义即可,因此:
isEven :: Int -> Bool
isEven x = divisibleBy x 2
或者我们可以通过使用flip::(a->b->c)->b->a->c来省略x
参数:
isEven :: Int -> Bool
isEven = flip divisibleBy 2
对于divisibleBy
函数也是如此,我们可以将其重写为:
divisibleBy :: Int -> Int -> Bool
divisibleBy x y = mod x y == 0
或不带参数:
divisibleBy :: Int -> Int -> Bool
divisibleBy = ((0 ==) .) . mod
交换可除数的参数
不过,交换函数的参数看起来更像Haskell,因此我们可以将其写成:
isEven :: Int -> Bool
isEven x
| (divisibleBy x 2) = True
| otherwise = False
divisibleBy :: Int -> Int -> Bool
divisibleBy x y = mod y x == 0
因为现在我们可以定义一个函数除以2
,该函数将检查任何参数该数字是否可除以2
在这种情况下,isEven
函数如下所示:
isEven :: Int -> Bool
isEven = divisibleBy 2
错误信息已经说明了这一点。你写道:
isEven :: Int -> Bool
isEven x
| (divisibleBy x 2) == 0 = True
| otherwise = False
但现在它仍然不雅观:我们不必检查条件是否保持返回True
,否则False
,我们只需返回定义即可,因此:
isEven :: Int -> Bool
isEven x = divisibleBy x 2
或者我们可以通过使用flip::(a->b->c)->b->a->c来省略x
参数:
isEven :: Int -> Bool
isEven = flip divisibleBy 2
对于divisibleBy
函数也是如此,我们可以将其重写为:
divisibleBy :: Int -> Int -> Bool
divisibleBy x y = mod x y == 0
或不带参数:
divisibleBy :: Int -> Int -> Bool
divisibleBy = ((0 ==) .) . mod
交换可除数的参数
不过,交换函数的参数看起来更像Haskell,因此我们可以将其写成:
isEven :: Int -> Bool
isEven x
| (divisibleBy x 2) = True
| otherwise = False
divisibleBy :: Int -> Int -> Bool
divisibleBy x y = mod y x == 0
因为现在我们可以定义一个函数除以2
,该函数将检查任何参数该数字是否可除以2
在这种情况下,isEven
函数如下所示:
isEven :: Int -> Bool
isEven = divisibleBy 2
查看divisibleBy
的类型和定义,并确定它何时可以返回0
(而不是True
或False
)。HaskellBool
与Int
的区别与IO Char
或任何其他类型的区别一样。PutisEven x=mod x 2==0
,删除其余部分。查看divisibleBy
的类型和定义,确定它何时可以返回0
(而不是True
或False
)。HaskellBool
与Int
的区别与IO Char
或任何其他类型一样。PutisEven x=mod x 2==0
,删除其余部分。对于isEven x=flip divisibleBy 2
,您只需要isEven=…
对吗?@code学徒:正确,感谢您发现这一点:)@chepner,你可以写x`divisibleBy`2
,它比divisibleBy`x2
读起来更好。尽管将其用作中缀运算符是支持原始顺序的有力论据:)故事的寓意:命名事物很难。对于isEven x=flip divisibleBy 2
,你只需要isEven=…
对吗?@code学徒:正确,谢谢你发现了这一点:)@chepner或者,你可以写x`divisibleBy`2
,读起来比divisibleBy x2
更好。尽管将其用作中缀运算符是支持原始顺序的有力论据:)故事的寓意:命名事物是困难的。