避免显式记录键入

时间:2018-08-10 21:12:11

标签: record sml smlnj

假设我具有以下用于在理想化流上进行操作的功能:

fun Stream s = { pos = 0, row = 1, col = 0, str = s }
fun len { str, pos = _, row = _, col = _ } = String.size str

fun poke off { str, pos, row: int, col: int } =
  let val n = pos + off in
    if n >= 0 andalso n <= (String.size str) then SOME (String.sub(str, n)) else NONE
  end

这可以工作/编译,但是不幸的是我不得不用我不关心的信息来乱放我的函数定义。 row / col被忽略pokelen。但是,尽管通配符可以与len一起使用,但不能与poke一起使用。有没有一种方法可以重组这些功能,以便在不影响显式键入的情况下仍然能够进行模式匹配/解构?

1 个答案:

答案 0 :(得分:1)

如果为您的类型命名(例如stream),则可以更简单地引用它:

type stream = { pos : int, row : int, col : int, str : string }

fun Stream s = { pos = 0, row = 1, col = 0, str = s }

fun len ({ str, ... } : stream) = String.size str

fun poke off ({ str, pos, ... } : stream) =
  let val n = pos + off in
    if n >= 0 andalso n <= String.size str
    then SOME (String.sub (str, n))
    else NONE
  end

或者,或多或少等效:

datatype stream = STREAM of { pos : int, row : int, col : int, str : string }

fun Stream s = STREAM { pos = 0, row = 1, col = 0, str = s }

fun len (STREAM { str, ... }) = String.size str

fun poke off (STREAM { str, pos, ... }) =
  let val n = pos + off in
    if n >= 0 andalso n <= String.size str
    then SOME (String.sub (str, n))
    else NONE
  end