let versus bind in IO in Haskell
Inside do, let names a pure value while <- runs an action and binds its result.
-- An IO action that produces a value rather than printing one.
readTank :: IO Double
readTank = pure 61.5
main :: IO ()
main = do
-- let names a pure value; nothing is executed.
let capacity = 80.0 :: Double
-- <- runs the action and binds the result it yields.
level <- readTank
let percent = 100 * level / capacity
-- show turns a number into the String putStrLn needs.
putStrLn ("tank holds " ++ show level ++ " of " ++ show capacity)
putStrLn ("that is " ++ show percent ++ " percent full")
How it works
let capacity = 80.0 :: Doublebinds a number without performing any IO at all.level <- readTankexecutes the action and binds the Double it yields.showturns each number into the String thatputStrLndemands.
Keywords and builtins used here
DoubleIOdoletmainreadTank
The run, in numbers
- Lines
- 14
- Characters to type
- 496
- Tokens
- 65
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 52 seconds.
Step 2 of 3 in IO basics, step 23 of 27 in Language basics.