typestar

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

  1. let capacity = 80.0 :: Double binds a number without performing any IO at all.
  2. level <- readTank executes the action and binds the Double it yields.
  3. show turns each number into the String that putStrLn demands.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in IO basics, step 23 of 27 in Language basics.

← Previous Next →