Sunday, 15 May 2016

Haskell: interact: Interact with input

The interact function takes a function of type String->String as its argument, and whatever the input you entered is passed to this function as its argument, and the resulting string is output on the standard output device.

*Main> :t interact
interact :: (String -> String) -> IO ()


Sample.hs
countChars :: String -> String
countChars xs = "Total Characters are " ++ show (length xs)

main = do
        putStrLn "Enter some information"
        interact countChars

$ ghc Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, Sample.o )
Linking Sample ...
$ ./Sample
Enter some information
Hello PTR, How are you
Total Characters are 23


Once you entered some data to above program, signal an EOF to say that you are done entering input (in the console, this is Control-D on Unix/Mac systems, Control-Z on Windows), then it will give you the length.

You can modify program like below, which return length of string immediately after you press Enter.


Sample.hs
eachLine :: (String -> String) -> (String -> String)
eachLine f = unlines . map f . lines

inputLength :: String -> String
inputLength input = show $ length input

main = do
        putStrLn "Enter some information"
        interact (eachLine inputLength)

$ ghc Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, Sample.o )
Linking Sample ...
$ ./Sample
Enter some information
Hello How are you PTR
21
Oho is it....How is that happened
33
Take care Good Bye
18
^C



Previous                                                 Next                                                 Home

No comments:

Post a Comment