你碰上了irrefutable patterns
。正如书中提到的,普通的变量名和通配符_
是无可辩驳的模式的例子。另一个irrefutable patterns
更清楚地展示的例子:
data Fruit = Apple | Orange deriving (Show)
patternMatch f = case f of
something -> Apple
现在上面的程序类型检查带有警告。在 ghci 中:
ghci> patternMatch 2
Apple
ghci> patternMatch "hi"
Apple
所以基本上这个变量something
是一个无可辩驳的模式,可以匹配任何东西。
现在,回到你的例子:
whichFruit :: String -> Fruit
whichFruit f = case f of
apple -> Apple
orange -> Orange
这里的变量apple
和orange
是无可辩驳的模式。它们没有引用您已经创建的全局函数。实际上,您可以删除 and 的全局定义apple
并orange
编译它们以获得一个想法。无论您提供什么输入,您总是会得到Apple
上述代码的答案(因为它是一个无可辩驳的模式):
ghci > whichFruit "apple"
Apple
ghci > whichFruit "orange"
Apple
ghci > whichFruit "pineApple"
Apple
如何在 Haskell 的函数中使用全局变量?
这实际上很容易。只需在您的函数定义中使用它们。
data Fruit = Apple | Orange deriving (Show)
apple = "apple"
orange = "orange"
giveFruit :: Fruit -> String
giveFruit Apple = apple
giveFruit Orange = orange
在 ghci 中:
ghci> giveFruit Apple
"apple"
ghci> giveFruit Orange
"orange"
在函数定义中使用变量很简单。
如果我希望变量引用具有相同名称的全局变量,应该怎么做?
一种方法是使用整个模块名称来引用它。例子:
module Fruit where
data Fruit = Apple | Orange deriving (Show)
apple = "apple"
orange = "orange"
giveFruit2 :: Fruit -> String
giveFruit2 apple = Fruit.apple