You have hit upon irrefutable patterns
. As the book mentions, plain variable names and the wild card _
are examples of irrefutable patterns. Another example which will demonstrate irrefutable patterns
more clearly:
data Fruit = Apple | Orange deriving (Show)
patternMatch f = case f of
something -> Apple
Now the above program typechecks with an warning. In ghci:
ghci> patternMatch 2
Apple
ghci> patternMatch "hi"
Apple
So basically the variable something
is an irrefutable pattern which matches anything.
Now,coming back to your example:
whichFruit :: String -> Fruit
whichFruit f = case f of
apple -> Apple
orange -> Orange
Here the variable apple
and orange
are irrefutable patterns. They doesn't refer to the global function which you have already created. In fact you can remove the global definition of apple
and orange
and compile them in order to get an idea. Whatever input you give, you will always get Apple
as an answer for the above code (since it is an irrefutable pattern):
ghci > whichFruit "apple"
Apple
ghci > whichFruit "orange"
Apple
ghci > whichFruit "pineApple"
Apple
How to use a global variable within a function in Haskell ?
That's pretty easy actually. Just use them in your function definition.
data Fruit = Apple | Orange deriving (Show)
apple = "apple"
orange = "orange"
giveFruit :: Fruit -> String
giveFruit Apple = apple
giveFruit Orange = orange
In ghci:
ghci> giveFruit Apple
"apple"
ghci> giveFruit Orange
"orange"
Using the variable in the function definition is straight forward.
What should be done if I want the variable to refer to a global
variable owning the same name?
One way would be to use the entire module name to refer to it. Example:
module Fruit where
data Fruit = Apple | Orange deriving (Show)
apple = "apple"
orange = "orange"
giveFruit2 :: Fruit -> String
giveFruit2 apple = Fruit.apple