Haskell: Lax Boolean Operations

Does Haskell need to define a function like the following?

or True True = True or True undefined = True or True False = True or undefined True = True or undefined False = undefined or undefined undefined = undefined or False True = True or False undefined = undefined or False False = False 

I currently have no precedent (although this interests me), I'm just wondering if this is possible.

+7
source share
2 answers

Depending on your evaluation order (the order in which you check the values) you can write a lazy version:

 Prelude> True || undefined True Prelude> undefined || True *** Exception: Prelude.undefined Prelude> :t or or :: [Bool] -> Bool Prelude> or [True, undefined] True 

in fact, the default definition in Haskell will behave as Haskell is a lazy language.

However, there is no way to "skip" the value of undefined without first looking at the value that will evaluate it from below, which means that your expression will be undefined.

Remember that lazy meanings are ghosts inside them:

enter image description here

If you look inside the box, a ghost may come to you.

If bottom testing is important (for example, as part of testuite), you can treat them as exceptions and catch them . But you would not do it in a pure function.

+12
source

This is not possible with standard Haskell, but can be done with an unsafe trick implemented by the lub library by Conal Elliott.

Basically, you write two functions:

 orL True _ = True orL False x = x orR = flip orL 

and then you can define or ab as lub (minimum upper bound relative to the order of definition) orL ab and orR ab .

Quickly, he starts both calculations in parallel and selects the first that succeeds, killing the other.

Despite the fact that it works as you suggested, it has important disadvantages. First of all, lub is safe only if its arguments are consistent (equal if only the bottom). If you take lub True False , the result will be non-deterministic, which will violate cleanliness! Secondly, performance overheads when performing both calculations in parallel can become dominant in some conditions (try to calculate foldr or False large list, for example!).

+15
source

All Articles