I find I quite seldom come across situations where I need to use the where
clause. However, I do find that I have used it very occasionally in the past. When is the where
clause used (i.e. what situations is it used in)? Under what circumstances should I use it?
Areas to use with where clause in Haskell, let’s take a look at how we can use where clause or function in Haskell see below; 1) Inside function defection: Where clause can be used with a function definition, where we can dive the logic into smaller parts. This divination helps us to optimize the code as well.
The operator = is used to assign a value to a variable, e.g. phi = 1.618. The scope of such variables can be controlled by using let or where clauses. Another sense in which "variable" is used in Haskell is as formal parameters to a function.
If inside our function we have some complex logic or calculation then we can divide that logic into smaller parts using where keyword. Also where clause is responsible to generate the desired output as well. Where is a keyword or function which is available in Haskell, we do not require to use any external library for this to work.
There are two excellent answers to this question available on the Haskell Wiki as well:
http://haskell.org/haskellwiki/Declaration_vs._expression_style http://haskell.org/haskellwiki/Let_vs._Where
Both are used to create local definitions that perhaps make use of values passed into the scope of their enclosing function, and certainly are not available outside of the context of the enclosing function. They promote code reuse and minimize duplication. Given fix
and lambda, both can be desugared away entirely. Generally, I use where clauses whenever possible, and only tend to use let clauses for definitions inside a lambda or case block, or in do
notation, when making use of values extracted through <-
on previous lines. In general, I think declarative style is now much more prevalant than expression style in idiomatic modern Haskell code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With