tags:

views:

87

answers:

2

I have two functions:

lowerString :: [Char] -> [Char]
lowerString = filter (/='_')

upperString :: [Char] -> [Char]
upperString [] = []
upperString (x:xs) 
    | x == '_' = x : upperString (tail xs)
    | otherwise = ' ' : upperString(xs)

If I apply them on "_A_B_CDEF":

upperString "_A_B_CDEF" would return ___
lowerString "_A_B_CDEF" would return ABCDEF
(without the spaces)

The idea is to have "upperscored" letters (needed for a bigger exercise).

I never worked with Haskell Input/Output (actually this is my 5th day in Haskell). How do I write a function that receive a [Char] as input and prints the two strings as output ?

+2  A: 

I/O needs to be done in the IO monad. To read a string, use the getLine action, and to print it, use the putStrLn action, e.g.

main :: IO ()
main = do
  theInput <- getLine
  putStrLn (upperString theInput)
  putStrLn (lowerString theInput)

See http://book.realworldhaskell.org/read/io.html for how use do basic I/O in Haskell.

KennyTM
You might not want readLn as that requires your input to be quoted.
TomMD
+1  A: 

First, I would rewrite your functions like this:

lowerString :: String -> String
upperString :: String -> String
lowerString = filter (/= '_')
upperString = filter (== '_')

Or, if you need the behavior, that each second underscore might be skipped (like: upperString "_a__bc" == "__"), something like this:

upperString ('_': _ :xs) = '' : upperString xs upperString ('': "" ) = "" upperString ( _ : xs ) = ' ' : upperString xs upperString "" = ""

BTW, now the output of upperString differs from the function definition in your description, as the characters are no longer replaced by spaces, but simply stripped.

For your output problem: You have to do all output in the IO monad. This isn't really difficult, you can use a do block to cover this in an imperative look and feel. Any action which may do something to the environment, has the special type IO attached to the output, so you can only run them inside the IO monad itself, or inside a do block:

printStrings :: String -> IO () -- () is empty value
printStrings s = do
  putStrLn $ upperString s --This will be executed, like in an imperative language
  putStrLn $ lowerString s

Consider reading this wikibooks chapter about simple IO.

FUZxxl