Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

smlnj - What are the options SOME and NONE in SML?

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'?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The option data type is used if there is a possibility of something having no valid value.

For instance,

fun divide x y = if y == 0 then NONE else SOME (x / y)

could be used if you need to handle the special case of division by zero without resorting to exceptions.

TextIO.inputLine returns NONE when there is nothing more to read, and SOME l, where l 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

fun readlist (infile : string) =  
  let
      val ins = TextIO.openIn infile 
      fun loop indata = 
          case TextIO.inputLine indata of 
              SOME line => line :: loop indata 
            | NONE      => []
      val result = loop ins
  in 
     TextIO.closeIn ins;
     result
  end 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...