Home > Mobile >  How to replace "let/in" construction with "where" in IO () function in Haskell?
How to replace "let/in" construction with "where" in IO () function in Haskell?

Time:10-01

I am studying Haskell and trying my first IO functions. Here a simple program that calculates the area of a rectangle, it works fine:

squareCalc :: IO ()
squareCalc = do
  putStrLn "Pease enter the lenght"
  length <- getLine
  putStrLn "Pleas enter the width"
  width <- getLine
  let square = read length * read width
   in putStrLn ("The square is "    show square)

However, when I try to replace "let/in" with "where":

squareCalc2 :: IO ()
squareCalc2 = do
  putStrLn "Pease enter the lenght"
  length <- getLine
  putStrLn "Pleas enter the width"
  width <- getLine
  putStrLn ("The square is "    show square) 
    where
       square = (read length) * (read width)

the compiler returns an error error:

Variable not in scope: width :: String

I am wondering if there ever possible to use "where" in functions like this?

CodePudding user response:

Nope, it's not possible. Annoying. The closest you can get is to make the thing in the where block be a function.

squareCalc2 = do
    ...
    putStrLn ("The square is "    show (square length width))
    where square length width = read length * read width
  • Related