Asdren
Asdren

Reputation: 89

Recursive function with IO

I'm having problems with the next code, the idea is to make a function which returns a list of words from a file with the directory in a tuple.

gainData:: [FilePath] -> IO [([String],String)]
gainData[] = []
gainData(xz:xc) = do
    temp <- readFileP xz
    return ((temp,xz) : gainData xc)

The function readFileP gets a list with all the words of a file.

readFileP:: FilePath -> IO [String]

For example i would want to get

[(["word","word1"],"fileAddress"),(["word","word1"],"fileAddress2")]

I don't know what's the problem, can somebody tell me please? Thanks.

Upvotes: 2

Views: 306

Answers (1)

Bakuriu
Bakuriu

Reputation: 101909

You cannot do:

return ((temp,xz) : gainData xc)

The gainData function returns an IO [something] not just [something]. You have to first extract the value returned:

res <- gainData xc
return $ (temp,xz) : res

The varname <- action does the following:

  • It calls action, which in this case its gainData xc. This action returns an IO something
  • It "extracts" the something from the IO and assign it to varname

in fact it works with any Monad, not just IO.

Also, in the first definition you are returning [], but this is of type [something] while gainData should be of type IO [something] so you have to add a IO layer to it:

gainData [] = return []

return is "the opposite" of the <-. It takes a something and turns it into an IO something, which can be extracted using the <-.

Upvotes: 8

Related Questions