我是SML的新手(实际上是编程的人)。
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 ;
这是我在这里遇到的程序。如何使用SOME和NONE,以及如何使用“之前”?
最佳答案
如果可能存在某些无效值,则使用option
数据类型。
例如,
fun divide x y = if y == 0 then NONE else SOME (x / y)
如果您需要处理除以零的特殊情况而不求助于异常,则可以使用。
当没有更多要读取的内容时,
TextIO.inputLine
返回NONE
;如果有更多内容,则SOME l
返回l
,即其中已读取的行。before
是低优先级(所有功能中最低的)的infix函数,它首先评估其左手边,然后是右手边,然后返回左手边的值。它的类型为
'a * unit -> 'a
,即右侧仅用于其副作用。在这种情况下,它使代码比等价的代码更具可读性(看上去更实用)。
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
关于sml - SML中的SOME和NONE选项有哪些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24980801/