Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where does the `where` clause come in handy in Haskell

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?

like image 931
maclunian Avatar asked May 17 '11 14:05

maclunian


People also ask

How to use where clause or function in Haskell?

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.

What is the scope of a variable in Haskell?

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.

How to divide a function into smaller parts in Haskell?

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.


1 Answers

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.

like image 91
sclv Avatar answered Nov 29 '22 10:11

sclv