Hacker News new | ask | show | jobs
by yakubin 1546 days ago
Example program to show three ways of doing that:

  import System.Random

  randomInt :: IO Int
  randomInt = randomIO

  isEven1 :: Int -> Bool
  isEven1 n = (n `rem` 2) == 0

  isEven2 :: IO Int -> IO Bool
  isEven2 n = do
      m <- n
      return $ isEven1 m

  example1 :: IO ()
  example1 = do
      i1 <- randomInt
      let result1 = isEven1 i1
      putStrLn $ show result1

      i2 <- randomInt
      let result2 = isEven1 i2
      putStrLn $ show result2

      let result2' = isEven1 i2
      putStrLn $ show result2'

  example2 :: IO ()
  example2 = do
      result1 <- isEven2 randomInt
      putStrLn $ show result1

      result2 <- isEven2 randomInt
      putStrLn $ show result2

  randomIntIsEven :: IO Bool
  randomIntIsEven = isEven2 randomInt

  example3 :: IO ()
  example3 = do
      result1 <- randomIntIsEven
      putStrLn $ show result1

      result2 <- randomIntIsEven
      putStrLn $ show result2

  main :: IO ()
  main = do
      putStrLn "Example 1:"
      example1
      putStrLn "Example 2:"
      example2
      putStrLn "Example 3:"
      example3
In example1, result1 and result2 may differ, which is signalled by the arrow (instead of "="). result2 and result2' cannot differ, which is signalled by "=", where the right hand side is verbatim the same.

In example2, result1 and result2 may differ, which is signalled by "<-" (instead of "=").

In example3, result1 and result3 may differ, which is signalled by "<-" (instead of "="). Another argument here is that they may differ, because example3 is the same as example2, except it used randomIntIsEven in place of isEven2 randomInt. But we defined randomIntIsEven to be equal to isEven2 randomInt, so result1 and result2 being able to be different in example2 but not in example3, or vice versa, would be a contradiction.