问题描述
功能:
fn:'a - > 'b
现在有没有可以定义的功能,并且有这种类型?
标准ML中有两种可能的函数签名实现。一个使用异常,另一个使用递归:
val增加:'a - > 'b =
fn a =>提高失败一些错误;
(*无限循环;满足类型签名,*)
(*但不会产生任何东西。*)
val rec循环:'a - > 'b =
fn a =>循环一次;
第一个解决方案可能对定义辅助函数很有用,比如 bug ,这可以节省几个关键笔划:
fun bug msg = raise失败(BUG:^ MSG);
另一个解决方案可能对定义服务器循环或REPL很有用。
在Basis库中, OS.Process.exit 是一个返回未知泛型类型'a :
- OS.Process.exit;
val it = fn:OS.Process.status - > 'a
类型为 val repl = fn:unit - > 'a :
fun repl()=
let
val line = TextIO.inputLine TextIO.stdIn
in
case line of
NONE => OS.Process.exit OS.Process.failure
|一些:q \ n=> OS.Process.exit OS.Process.success
| SOME line => (TextIO.print line; repl())
end
你也许会觉得有用有关Haskell的类型签名的问题forever function a>。
The function:
fn : 'a -> 'b
Now, are there any functions which can be defined and have this type?
There are two possible implementations for that function signature in Standard ML. One employs exceptions, the other recursion:
val raises : 'a -> 'b = fn a => raise Fail "some error"; (* Infinite looping; satisfies the type signature, *) (* but won't ever produce anything. *) val rec loops : 'a -> 'b = fn a => loops a;
The first solution may be useful for defining a helper function, say bug, which saves a few key strokes:
fun bug msg = raise Fail ("BUG: " ^ msg);
The other solution may be useful for defining server loops or REPLs.
In the Basis library, OS.Process.exit is such a function that returns an unknown generic type 'a:
- OS.Process.exit; val it = fn : OS.Process.status -> 'a
A small echo REPL with type val repl = fn : unit -> 'a:
fun repl () = let val line = TextIO.inputLine TextIO.stdIn in case line of NONE => OS.Process.exit OS.Process.failure | SOME ":q\n" => OS.Process.exit OS.Process.success | SOME line => (TextIO.print line ; repl ()) end
You might also find useful this question about the type signature of Haskell's forever function.
这篇关于ml函数的类型fn:'a - > “b的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!