在一节中,与第三章 of real 中的变量不正确地匹配,有一个示例如下:
-- file: ch03/BogusPattern.hs
data Fruit = Apple | Orange
apple = "apple"
orange = "orange"
whichFruit :: String -> Fruit
whichFruit f = case f of
apple -> Apple
orange -> Orange解释说,在case f of部件中,apple和orange不像函数声明之前定义的那样被视为全局变量。它们是局部变量,我认为如果没有局部变量拥有与全局变量相同的名称,全局变量就不会被隐藏。
发布于 2014-05-17 10:54:56
这里的主要问题是模式匹配中的变量总是引入新变量,而不是引用现有变量。您的问题与全局变量和局部变量无关。
如果要将f的值与某些变量(如模式中的apple )的值相匹配,则需要使用模式保护和相等测试。例如。
whichFruit f
| f == apple = Apple
| f == orange = Orange发布于 2014-05-17 09:53:26
你偶然发现了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是无可辩驳的模式。它们并不是指您已经创建的全局函数。实际上,您可以删除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.applehttps://stackoverflow.com/questions/23709602
复制相似问题