完成以下函数定义:
-- maxi x y returns the maximum of x and y
我应该在不使用Haskell 中的"最大"函数的情况下完成此任务。
maxi :: Integer -> Integer -> Integer
maxi x y
|x > y = x
|y > x = y
然后我不明白如何进行。如何测试代码是否有效?它看起来有点正确吗?
您可以通过调用函数来测试函数(您自己或使用测试库,如QuickCheck
(。例如,我们可以将源代码存储在一个文件(名为test.hs
(:
-- test.hs
maxi :: Integer -> Integer -> Integer
maxi x y
|x > y = x
|y > x = y
然后,例如,我们可以使用ghci
命令启动 GHC 交互式会话,并加载将文件名作为参数传递的文件。然后我们可以称之为:
$ ghci test.hs
GHCi, version 8.0.2: http://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling Main ( test.hs, interpreted )
Ok, modules loaded: Main.
*Main> maxi 2 9
9
*Main> maxi 3 5
5
*Main> maxi 7 2
7
正确吗?没有。这里有一个没有涵盖的情况:如果x
和y
相同,那么它会引发一个错误:
*Main> maxi 7 7
*** Exception: test.hs:(4,1)-(6,13): Non-exhaustive patterns in function maxi
我们可以通过使用otherwise
作为最后一次检查来修复它,这将始终是True
的(实际上它是True
的别名(。您可以将otherwise
视为else
:
-- test.hs
maxi :: Integer -> Integer -> Integer
maxi x y
| x > y = x
| otherwise = y