Haskell - 编码'最大'而没有实际使用函数[beginner]

Tob*_*rdt 1 haskell

完成以下函数定义:

    -- maxi x y returns the maximum of x and y
Run Code Online (Sandbox Code Playgroud)

我应该在使用Haskell中的'maximum'函数的情况下完成此任务.

maxi :: Integer -> Integer -> Integer
maxi x y
 |x > y = x
 |y > x = y 
Run Code Online (Sandbox Code Playgroud)

然后我不明白该怎么做.如何测试代码是否有效?它看起来有点正确吗?

Wil*_*sem 8

您可以通过调用该函数(您自己或使用测试库等QuickCheck)来测试该函数.例如,我们可以将源代码存储在一个文件中(命名test.hs):

-- test.hs

maxi :: Integer -> Integer -> Integer
maxi x y
 |x > y = x
 |y > x = y 
Run Code Online (Sandbox Code Playgroud)

然后我们可以例如通过使用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 
Run Code Online (Sandbox Code Playgroud)

这是对的吗?.有没有被覆盖这里的情况:如果xy是相同的,那么它会引发错误:

*Main> maxi 7 7
*** Exception: test.hs:(4,1)-(6,13): Non-exhaustive patterns in function maxi
Run Code Online (Sandbox Code Playgroud)

我们可以使用otherwise最后一次检查来修复它,它总是True(事实上​​它是别名True).你可以看到otherwiseelse:

-- test.hs

maxi :: Integer -> Integer -> Integer
maxi x y
 | x > y = x
 | otherwise = y 
Run Code Online (Sandbox Code Playgroud)