From 044c2eda07c10a235057d947ce7347653b7d99b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20G=C3=A9lineau?= Date: Sun, 15 Feb 2015 11:09:01 -0500 Subject: [PATCH] Explain what type errors have to do with purity To someone who isn't yet familiar with Haskell's syntax, the string concatenation example looks like the type error is that a string is being concatenated with a function. Here is an example which better explains how using an IO computation in a pure context can lead to a type error. As a bonus, the new text no longer claims that "you cannot mix and match purity with impurity". It's not true: we can mix them, but the result must be marked as impure. --- src/HL/View/Home/Features.hs | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/src/HL/View/Home/Features.hs b/src/HL/View/Home/Features.hs index bd6968a..e481039 100644 --- a/src/HL/View/Home/Features.hs +++ b/src/HL/View/Home/Features.hs @@ -38,20 +38,26 @@ purefunc = \ mutate any of its arguments.") haskellPre "square :: Int -> Int\n\ \square x = x * x" - p_ (do "The following string concatenation is okay:") - haskellPre "\"Hello: \" ++ \"World!\" " - p_ (do "The following string concatenation is a type error:") - rejectedHaskellPre "Type error" "\"Name: \" ++ getLine" - p_ (do "Because " - code_ "getLine" - " has type " - code_ "IO String" - " and not " - code_ "String" - ", like " - code_ "\"Name: \"" - " is. So by the type system you cannot mix and \ - \match purity with impurity.") + p_ (do "The following function takes an integer, prints the list of all numbers \ + \from zero to that number, and returns its argument. Printing is an " + code_ "IO" + " side-effect, so the function's type must indicate that it describes an " + code_ "IO" + "computation.") + haskellPre "printUpTo :: Int -> IO Int\n\ + \printUpTo x = do print [0..x]\n\ + \ return x" + p_ (do "Since " + code_ "Int" + " and " + code_ "IO Int" + " are different types, the type system can guarantee that a function of type " + code_ "Int -> Int" + " will not trigger any surprising side-effect.") + haskellPre "printUpToSquare :: Int -> IO Int\n\ + \printUpToSquare x = printUpTo (x * x) -- typechecks" + rejectedHaskellPre "Type error" "printUpToSquare :: Int -> Int\n\ + \printUpToSquare x = printUpTo (x * x)" statically :: Html () statically =