Haskell Return and Binding
Binding with the arrow <- takes the result out of an IO action and gives it a name. The word return does the reverse and wraps a plain value as the result of an action.
The arrow takes a result out
The storedName action holds a result. The arrow binds that result to name in main.
storedName :: IO String
storedName = return "Ana"
main :: IO ()
main = do
name <- storedName
putStrLn ("Hello, " ++ name)return does not stop the program
The first line binds a value with return. The actions after it still run.
main :: IO ()
main = do
word <- return "Start"
putStrLn word
putStrLn "Still running"return wraps a worked out value
The triple action wraps three times its input. The arrow takes that result out in main.
triple :: Int -> IO Int
triple n = return (n * 3)
main :: IO ()
main = do
result <- triple 7
print resultExample
greet :: IO String
greet = do
name <- getLine
return ("Hello, " ++ name)
main :: IO ()
main = do
message <- greet
putStrLn messageKey points
- Arrow binding: name <- action takes the result out of the action and binds it to the name.
- Scope: a name bound with <- can be used by later lines in the same do block.
- return: a function that wraps a plain value as the result of an IO action.
- No stopping: return does not end the program, and later actions still run.
- Action result: the last action in a do block gives the result of the whole block.
- IO String: the type of an action whose result is a String.
In this example, the typed line is Ana. Inside greet, the arrow binds that line to name, and return wraps the joined greeting as the result of greet. In main, the arrow binds that result to message, and putStrLn prints it.
Note
return in Haskell only wraps a value, unlike the return word in many other languages.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does return "Hi" do in a function with type IO String?