'where' inside another expression

I can use let inside another expression.

 foo n = (let a = True in (\x -> a)) 3 foo' n | n == 1 = let a = True in a | n /= 1 = False 

But I can not do the same with where

 foo n = ((\x -> a) where a = True) 3 foo' n | n == 1 = a where a = True | n /= 1 = False 

1:20: parsing error at the input `where '

Is this really impossible in haskell or is it just my mistake?

+4
source share
4 answers

let is an expression, and where is a sentence. where attached to syntax constructs, let any expressions be used.

You could, of course, write this as follows:

 foo n = ((\x -> a)) 3 where a = True foo' n | n == 1 = a | n /= 1 = False where a = True 

or like this:

 foo n = (\a -> (\x -> a) 3) True 
+10
source

You need to put the where clause at the end:

 foo n = ((\x -> a)) 3 where a = True foo' n | n == 1 = a | n /= 1 = False where a = True 

The difference is that let is an expression, while where requires binding of some other construct. See let vs where

+4
source

let ... in ... is for introducing name bindings in an expression.

where is a convenient syntax for providing local helper definitions along with an equation. You can use it only as part of the equation (at the end), and not in the middle of an arbitrary expression.

Their use is not the same.

+1
source

The statement that let is an expression is a bit like what seems to me; in the do block, this statement, although we say that there is the abbreviation let ... in . Fact that i think

  let_in_ :: Statement -> Expression -> Expression _where_ :: Statement -> Statement -> Statement 

Thus, the first part of a let is an operator and can be modified using where . For example,

  foo n = (let a = b where b = True in (\x -> a)) 3 bip = do let a = b where b = let c = d where d = True in c return a 

Similarly, we can say something like this:

  case_of_ :: Expression -> [Statement] -> Expression 

for example

 zx = case even x of True -> d where d = x + 1 False -> w - 1 where w = let a = x in a + 1 
0
source

Source: https://habr.com/ru/post/1438757/


All Articles