Home > Software design >  Scope of where clause within let..in
Scope of where clause within let..in

Time:07-07

encode :: String -> String
encode xs =
  let s = normalize xs
   in case s of
        [] -> []
        _ -> encode' s row col
        where row = isqrt (length s)
              col = length s `div` row

This gives the error "Variable not in scope: s". It seems the where clause within let..in can't see the variable s defined earlier.

How can I rewrite this?

CodePudding user response:

The where is defined at the function level, since s is not defined at that level, it thus can not access s. You can add extra declarations in the head of the let … in … level:

encode :: String -> String
encode xs =
  let s = normalize xs
      row = isqrt (length s)
      col = length s `div` row
   in case s of
        [] -> []
        _ -> encode' s row col

Or move everything to a where clause:

encode :: String -> String
encode xs = case s of
        [] -> []
        _ -> encode' s row col
  where s = normalize xs
        ns = length s
        row = isqrt ns
        col = ns `div` row
  • Related