`

haskell - Input and Output - helloworld

阅读更多

We've mentioned that Haskell is a purely functional language. Whereas in imperative languages you usually get things done by giving the computer a series of steps to execute, functional programming is more of defining what stuff is. In Haskell, a function can't change some state, like changing the contents of a variable (when a function changes state, we say that the function has side-effects). The only thing a function can do in Haskell is give us back some result based on the parameters we gave it. If a function is called two times with the same parameters, it has to return the same result. While this may seem a bit limiting when you're coming from an imperative world, we've seen that it's actually really cool. In an imperative language, you have no guarantee that a simple function that should just crunch some numbers won't burn down your house, kidnap your dog and scratch your car with a potato while crunching those numbers. For instance, when we were making a binary search tree, we didn't insert an element into a tree by modifying some tree in place. Our function for inserting into a binary search tree actually returned a new tree, because it can't change the old one.

 

 It turns out that Haskell actually has a really clever system for dealing with functions that have side-effects that neatly separates the part of our program that is pure and the part of our program that is impure, which does all the dirty work like talking to the keyboard and the screen. With those two parts separated, we can still reason about our pure program and take advantage of all the things that purity offers, like laziness, robustness and modularity while efficiently communicating with the outside world.

 

what will be covered by this post includes the following. 

  • hello world and how to run the hello world program 
  • type of putStrLn and getLine
  • the do monad, an introduction 
  • IO binding such as name <- getLine, don't confuse this with the name = getLine
  • let binding in the do monads
  • continuous reading from console - recursion and forever
  • every if has a matching else - if condition then I/O else I/O action 
  • return statement in the do monads
  • putChar, putStr, and print, getChar
  • when, sequence and mapM and mapM_.
  • forver, and forM (to create I/O action)

 

Helloworld and run haskell program 

We will start by inspecting the helloworld program . 

 

a very simple hello world program is as such .

main = putStrLn "hello, world"  

 

you generally can run the applicaiton in two ways. 

1. compile the code to native code, and run the native code. 

$ ghc --make helloworld  
[1 of 1] Compiling Main             ( helloworld.hs, helloworld.o )  
Linking helloworld ...  

 and then you run it 

$ ./helloworld  
hello, world  

 2. run it as a script 

runhaskell helloworld.hs

 

type of putStrLn and getLine

If we check the type of putStrLn and getLine, 

 

putStrLn

 

ghci> :t putStrLn  
putStrLn :: String -> IO ()  
ghci> :t putStrLn "hello, world"  
putStrLn "hello, world" :: IO ()  

 

 

which means that the putStrLn takes a string, and returns an IO action which has a result type of ()((i.e. the empty tuple, also know as unit).). 

getLine

 

ghci> :t getLine  
getLine :: IO String  

 what does this mean getLine is an I/O action that contains a result type of String. 

 

 

then let's see how we can use the do nomand and the I/O binding. here is the code.

 

 

main = do 
   putStrLn "Hello, what's your name?"
   name <- getLine
   putStrLn("Hey " ++ name ++ ",you rock!")

 

 

the code name <- getLine, is get the resut of the getLine I/O action and return the values to name, it is different to the following. 

 

nameTag = "Hello, my name is "  ++ getLine

 only gives a name to the I/O action. 

 

 

Let binding in do block 

We have covered in pattern matching that we can use the let...in... binding. we can use the "let" binding as well. here is the code .

 

 

import Data.Char

main = do 
   putStrLn "What's your first name?"
   firstName <- getLine
   putStrLn "What's  your last name ?"
   lastName <- getLine 
   let bigFirstName = map toUpper firstName
       bigLastName = map toUpper lastName
   putStrLn $ "hey " ++ bigFirstName ++ " " ++ bigLastName ++ ", how are you?" 

 

 

If we want to achive something that continous reading from the command line, an example is as follow, (we will examine the problem again when we coveres the forever monad)

 

main = do   
    line <- getLine  
    if null line  
        then return ()  
        else do  
            putStrLn $ reverseWords line  
            main  
  
reverseWords :: String -> String  
reverseWords = unwords . map reverse . words  

 

 

in the example above the code continous read from the same console, and then put the result to the console.

 

while you can do the same things with the forever, 

 

-- file 
--  forever
-- descrpition: 
--    takes an I/O action and returns an I/O action that just repeats the I/O action it got forever. It's located in Control.Monad

import Control.Monad  
import Data.Char  
  
main = forever $ do  
    putStr "Give me some input: "  
    l <- getLine  
    putStrLn $ map toUpper l  

 

if-else should be paired

 

 

We might have noticed that we have written with every if statement an else statement, the reason why?emember that in Haskell, every if must have a corresponding else because every expression has to have some sort of value. We make the if so that when a condition is true (in our case, the line that we entered is blank), we perform one I/O action and when it isn't, the I/O action under the else is performed. That's why in an I/O do block, ifs have to have a form of if condition then I/O action else I/O action.

 

Let's see some examples which has one return statement. 

 

-- file 
--   return_haskell.hs
-- description:
--   dive into the return statement

-- return do not cause the block to end
main = do  
    return ()  
    return "HAHAHA"  
    line <- getLine  
    return "BLAH BLAH BLAH"  
    return 4  
    putStrLn line  

-- return is like the opposite of <- 

main = do  
    a <- return "hell"  
    b <- return "yeah!"  
    putStrLn $ a ++ " " ++ b  

-- return can be replaced by the let binding, so sometimes the return statement is redundant

main = do  
    let a = "hell"  
        b = "yeah"  
    putStrLn $ a ++ " " ++ b  

 

 

putStr,putChar and print. 

 

then we will examine the putStr,putChar and print. 

 

 

main = do  putStr "Hey, "
           putStr "I'm "
           putStrLn "Any!"

 

 

 

--- it is maybe anarchasim

main = do putChar 't'
          putChar 'e'
          putchar 'h'

 and 

 

 

main = do print True 
          print 2
          print "haha"
          print 3.2
          print [3, 4, 3]

 

 

so, putStr print a string, putChar print a single character, and print will takes a type which is instance of Show, and then print the representation . 

 

and below is the getChar call. 

 

main = do 
   c <- getChar
   if c /= ' ' 
      then do 
        putChar c 
        main 
       else return ()

 

 

When and sequence 

when and sequence are calls which are from Control.Monad, it gives flow control, but they are actually some functions., 

examples are as below. 

-- file 
-- when_monad.hs
-- descrpition: 
--   the Control.Monad

import Control.Monad

main =do 
   c <- getChar
   when (c  /= ' ') $ do 
      putChar c 
      main

 and Sequence function. 

-- file 
--  sequence_io.hs
-- descrpition: 
--   the sequence  takes a list of I/O actions and returns an I/O actions that will perform those actions one after the other. 


-- main = do 
--     a <- getLine
--     b <- getLine  
--     c <- getLine  
--     print [a,b,c] 


main = do 
   rs <- sequence [getLine, getLine, getLine]
   print rs


-- below won't create an I/O action, it will create a list of I/O actions, because that is like writing 
-- map print [1, 2, 3, 4]
-- it is like 
-- [print 1, print 2, print 3, print 4]
sequence (map print [1,2,3,4,5])

 

mapM and mapM_

 

mapM takes a function and a list, maps the function over the list and then sequences it.mapM_ does the same, only it throws away the result later. We usually use mapM_ when we don't care what result our sequenced I/O actions have.

 

ghci> mapM print [1,2,3]  
1  
2  
3  
[(),(),()]  
ghci> mapM_ print [1,2,3]  
1  
2  
3  

 

forever

we have discussed the forever function, we will skip this one for now. 

 

forM

-- file 
--  forM_io.hs
-- descrpition: 
--   (located in Control.Monad) is like mapM, only that it has its parameters switched around.

import Control.Monad  

main = do   
    colors <- forM [1,2,3,4] (\a -> do  
        putStrLn $ "Which color do you associate with the number " ++ show a ++ "?"  
        color <- getLine  
        return color)  
    putStrLn "The colors that you associate with 1, 2, 3 and 4 are: "  
    mapM putStrLn colors  

 

so it basically create an IO actions, whose result we bind to colors. and we can do some action like print on the I/O actions. 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics