Haskell - 编码 'maximum' 而没有实际使用函数 [初学者]

标签 haskell

完成如下函数定义:

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

然后我们可以启动 GHC 交互式 session ,使用 ghci 命令并加载文件,将文件名作为参数传递。然后我们可以调用它:

$ 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 

关于Haskell - 编码 'maximum' 而没有实际使用函数 [初学者],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52272608/

相关文章:

haskell - 如何在 Yesod-Persistent 中使用记录语法

haskell - 在 monad 之后学习 Haskell 的下一步是什么?

haskell - 产生功能依赖的动机

haskell - 欧拉计划 : A (much) better way to solve problem #5?

haskell - 在GHC RTS的调度程序中,为什么要将功能标记为免费?

list - 用于验证括号匹配的 Haskell 函数

haskell - Haskell 中编译代码和 ghci 之间的差异

haskell - 尾递归,我应该在 Haskell 中使用它吗

Haskell 从文件 IO 返回惰性字符串

haskell - 如何告诉 myproj.cabal 使用我在 ~/.cabal 中安装的软件包?