Our
Our

Reputation: 1035

How to use `let` and `where` together?

I have the following code

initModel :: [Double] -> Model
initModel xs = do
 let weights = [f x | x <- xs]
     biases = [g x | x <- xs]

and I would like to define f and g by adding a where clause at the end of the initModel function. But, when I added like this

initModel :: [Double] -> Model
initModel xs = do
 let weights = [f x | x <- xs]
     biases = [g x | x <- xs]
  where
   f x = x
   g x = x
 Model weights biases

The last line gives Parse error on input 'Model' error. I have tried many combinations of indentations for the where clause but none has worked so far.

Upvotes: 0

Views: 188

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152837

The following shows some possible choices:

initModel xs = do
  let weights = [f x | x <- xs]
        where f x = x
      biases = [g x | x <- xs]
        where
          g x = x
  Model weights biases

initModel xs = do
  let weights = [f x | x <- xs]
      biases = [g x | x <- xs]
  Model weights biases
  where
  f x = x
  g x = x

In general: where must be attached to a binding (an equality or a clause in a case), and therefore indented more than that binding; and any bindings inside the where must be indented at least as much as any enclosing block (more than the enclosing block if you want to continue the enclosing block later).

Upvotes: 5

Related Questions