add something to a list
Sun, 17 Feb 2002 11:38:11 +0000
On Sunday 17 February 2002 08:20, christophe certain wrote:
> I'm a poor lonesome newbie in Haskell world, and I would like to add a
> string typed on the prompt to a list of strings which is already defined.
> It would look like something like :
> type Path = [String]
> currentPath = 
> getpiece ::IO String
> getpiece = do c <-getLine
> return c
> putpiece:: String->Path
> putpiece a = a:currentPath
> and then I could combine the two functions, but obviously it doesn't work.
> I dare understand that it's impossible isn't it ?
> Maybe the only way is to create a new [String] each time I want to add a
> new string ? No ?
> Christophe Certain
You seem to expect currentPath to be updated by putpiece? This won't happen
in Haskell. Once you've declared
it will always be .
Values never change. If you want the functional equivalent of accumulator
variables they have to be an argument of a recursive function. So try this..
getPath :: Path -> IO Path
getPath currentPath = do
piece <- getLine
if piece == "" then return currentPath
else getPath (piece:currentPath)
initialCurrentPath = 
main :: IO ()
main = do
path <- getPath initialCurrentPath
putStrLn (show path)