I am new to SML (and programming, actually).
fun readlist (infile : string) =
let
val
ins = TextIO.openIn infile
fun loop ins =
case TextIO.inputLine ins of
SOME line => line :: loop ins
| NONE => []
in
loop ins before TextIO.closeIn ins
end ;
This is a program I encountered here. How do I use SOME and NONE, and how to use 'before'?
Some('a)
andNone
are part of theOption
datatype.Option
is an algebraic or compound data structure found in SML's Basis Library. More on the Option data type at Wikipedia. The big idea is, allow a function to return the valueNone
when it doesn't make sense for the function to return a value of the type which the programmer really cares about.In the case of your user defined function
readlist
the important data is the string. But at some point, the program hits the end of the file and reads a value interpreted asEOF
instead of a string.Think about
TextIO.openIn
as a function that opens a stream and searches it for strings. Each time it finds a string, it returns anoption(string)
. When it does not find a string, it returnsNone
. Because both are part of theOption(string)
datatype,TextIO.openIn
only returns a single type.A related concept in SML is user-defined datatypes. Both the
option
datastructure and user-defined data types provide flexibility within SML's static type system in a somewhat similar manner to the way objects are used in statically typed object oriented languages.The
option
data type is used if there is a possibility of something having no valid value.For instance,
could be used if you need to handle the special case of division by zero without resorting to exceptions.
TextIO.inputLine
returnsNONE
when there is nothing more to read, andSOME l
, wherel
is the line it has read, when there is.before
is a low-precedence (the lowest of all) infix function that first evaluates its left hand side, then the right hand side, and then returns the value of the left hand side.It has type
'a * unit -> 'a
, i.e. the right hand side is used only for its side effects.In this case, it makes the code slightly more readable (and functional-looking) than the equivalent