On Fri, Jun 10, 2011 at 4:13 PM, Daniel Fischer <daniel.is.fischer@googlemail.com> wrote:
On Friday 10 June 2011, 13:49:23, Dmitri O.Kondratiev wrote:
> On Thu, Jun 9, 2011 at 11:31 AM, Max Bolingbroke
> <batterseapower@hotmail.com
>
> > wrote:
> >
> > If you want plain text serialization, "writeFile "output.txt" . show"
> > and "fmap read (readFile "output.txt")" should suffice...
> >
> > Max
>
> This code works:
>
> main = do
>      let xss = [[1,2,3],[4,5,6],[7,8],[9]]
>      writeFile "output.txt" (show xss)
>      line <- readFile "output.txt"
>      let xss2 = read line :: [[Int]]
>      print xss2
>
> As soon as complete file is returned as a single line, using 'fmap'
> does not make sense here:
>      line <- readFile "output.txt"
>      let xss2 = fmap read line
>
>  When to use 'fmap'?

   xss2 <- fmap read (readFile "output.txt")

or

   xss2 <- read `fmap` readFile "output.txt"

But it might be necessary to tell the compiler which type xss2 ought to
have, so it knows which `read' to invoke, if it can't infer that from later
use.


Two questions:
1) Why to use 'fmap' at all if a complete file is read in a single line of text?

2) Trying to use 'fmap' illustrates 1) producing an error (see below):
main = do
     let xss = [[1,2,3],[4,5,6],[7,8],[9]]
     writeFile "output.txt" (show xss)
     xss2 <- fmap read (readFile "output.txt") :: [[Int]]
     print xss2

== Error:
 Couldn't match expected type `[String]'
             with actual type `IO String'
 In the return type of a call of `readFile'
 In the second argument of `fmap', namely `(readFile "output.txt")'
 In a stmt of a 'do' expression:
     xss2 <- fmap read (readFile "output.txt") :: [[Int]]