I have a very simple question. I’d like to use a where clause after a bloc of code that uses bind operators but I get a compilation error.
Here is a simple example:
main =
putStrLn "where clause test:" >>
return [1..10] >>= \list ->
print list'
where list' = reverse list -- test1.hs:5:28: Not in scope: `list'
I can use a let clause for list’ as in
main =
putStrLn "where clause test:" >>
return [1..10] >>= \list ->
let list' = reverse list -- works of course
in print list'
but I’d really like it if I could use a where clause…
I also tried with do notation
main = do
putStrLn "where clause test:"
list <- return [1..10]
print list'
where list' = reverse list --test3.hs:5:30: Not in scope: `list'
Same problem. Can I use a where clause in these circumstances?
As ephemient explains, you can’t use
whereclauses the way you do.The error happens because in this code:
The
where-clause is attached to the main function.Here’s that same function with more parentheses:
I think its fairly obvious why you get the “
out of scope” error: The binding forlistis deep inside themainexpression, not something thewhereclause can reach.What I usually do in this situation (and I’ve been bitten by the same thing a bunch of times). I simply introduce a function and pass the
listas an argument.Of course, I imagine your actual code in the
ffunction is a lot more that justreverseand that’s why you want it inside awhereclause, instead of an inlineletbinding. If the code inside theffunction is very small, I’d just write it inside theletbinding, and wouldn’t go through the overhead of introducing a new function.