0

I have to write a code that takes integer list and writes them to a file. At the same time it returns true if the element is written, else false if it is not written.

I wrote something like

fun writetofile([],sfile)= false
|writetofile((l:int)::ls, sfile)=
    let 
    val outs=TextIO.openOut(sfile) 
    fun writeinline(outs,[])=(false;TextIO.closeOut(outs))
    |writeinline(outs,(l:int)::ls)=(true;TextIO.output(outs,(Int.toString(l)^"\n"));writeinline(outs,ls))
    in
    writeinline(outs,l::ls)  before
    TextIO.closeOut(outs)
    end
    ;

I got following error:

Error: right-hand-side of clause doesn't agree with function result type [tycon mismatch]
  expression:  unit
  result type:  bool
  in declaration:
    writeNums =
      (fn (nil,sfile) => true
        | (:: <pat>,sfile) =>
            let val <binding>
                val <binding> in (<exp>; <exp>) end)
700resu
  • 259
  • 6
  • 16

2 Answers2

2

The body of a function must have the type specified in the function-result type constraint.

L.Grillo
  • 960
  • 3
  • 12
  • 26
1

The base case of writetofile has type bool while the inductive case has type unit due to TextIO.closeOut(outs); so they don't agree on a return type for the function.

If you would like to return bool in the inductive case, you need something like TextIO.closeOut(outs); true.

By the way, your writeinline function always return unit so you don't need unused false, true values. Here is a corrected version:

fun writetofile([], sfile) = false
  | writetofile((l:int)::ls, sfile) =
    let 
       val outs = TextIO.openOut(sfile) 
       fun writeinline(outs,[]) = TextIO.closeOut(outs)
         | writeinline(outs, l::ls)= ( TextIO.output(outs (Int.toString(l)^"\n"));
                                       writeinline(outs, ls) )
    in
       ( writeinline(outs, l::ls);
         TextIO.closeOut(outs);
         true )
    end
pad
  • 41,040
  • 7
  • 92
  • 166
  • yes. i figured that out somehow before your post but still I dont know why writing true before let is different from writing after textio.closeOut(outs); Can you help me with this? I posted it somewhere else but, how to "handle" or return [] if a file is not found. Not in above case but while writing to file. If file is not existant The exception Io is raised. I need to handle it to return empty list. I wrote handle Io=>[] but does not work. – 700resu Oct 22 '12 at 15:21
  • For handling exception, check out this question http://stackoverflow.com/questions/4497243/handling-exceptions-in-ml . I suggest you start with a very simple example and try to add exception handling. If you have any specific problem, you can post a question here so people can help. – pad Oct 22 '12 at 15:38