How to use variable from do block assignment line in a where clause?

后端 未结 1 1730
青春惊慌失措
青春惊慌失措 2021-01-18 17:52

I have the following sample of code:

{-# LANGUAGE ScopedTypeVariables #-}

main = do
  putStrLn \"Please input a number a: \"
  a :: Int  <- readLn
  prin         


        
1条回答
  •  后悔当初
    2021-01-18 18:29

    Use let instead of where:

    {-# LANGUAGE ScopedTypeVariables #-}
    
    main = do
      putStrLn "Please input a number a: "
      a :: Int  <- readLn
      print a
    
      putStrLn "Please input a number b: "
      b :: Int  <- readLn
      print b
    
      let c = b^2
      putStrLn ("a+b+b^2:" ++ (show $ a+b+c))
    

    The reason for the problem is that variables in the where clause are in scope for all of main, but b isn't in scope until after b :: Int <- readLn. In general, where clauses can't reference variables bound inside of a do block (or anywhere to the right of the =, for that matter: e.g., f x = y*2 where y = x+1 is fine but f = \x -> y*2 where y = x+1 is not).

    0 讨论(0)
提交回复
热议问题