开发者

How can keyword "where" be defined globally in Haskell

开发者 https://www.devze.com 2023-04-04 14:40 出处:网络
I\'m reading 开发者_StackOverflow社区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?

I'm reading 开发者_StackOverflow社区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."


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消