Haskell-在不实际使用函数的情况下编写'maximum'编码[初学者]



完成以下函数定义:

-- 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 

正确吗?没有。这里有一个没有涵盖的情况:如果xy相同,那么它会引发一个错误:

*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 

最新更新