Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can keyword "where" be defined globally in Haskell

I'm reading the guide in learnyouahaskell.com . One sentence mentioned "where" can be shared globally, but no example was given, so where can I find some details, please?

"where bindings aren't shared across function bodies of different patterns. If you want several patterns of one function to access some shared name, you have to define it globally."

like image 966
jiyinyiyong Avatar asked Dec 04 '22 07:12

jiyinyiyong


2 Answers

From Chapter 4: Syntax in Functions:

where bindings aren't shared across function bodies of different patterns. If you want several patterns of one function to access some shared name, you have to define it globally.

Here is an illustration:

f (Left x) = double x
f (Right x) = double x
    where
    double x = 2 * x

The function f has a body for each of the patterns (Left x) and (Right x). The binding of double isn't shared across the function bodies, and therefore this code isn't valid Haskell.

If we want to access double from both of the function bodies, we have to move it out of the where clause:

double x = 2 * x

f (Left x) = double x
f (Right x) = double x

That's all that the quoted paragraph means.

like image 187
antonakos Avatar answered Jan 01 '23 19:01

antonakos


I think they mean that you have to define a new function globally instead of in a where.

like image 40
Ben Ruijl Avatar answered Jan 01 '23 19:01

Ben Ruijl