Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ml function of type fn : 'a -> 'b

The function:

fn : 'a -> 'b

Now, are there any functions which can be defined and have this type?

like image 599
Dor Katzelnick Avatar asked Dec 20 '25 08:12

Dor Katzelnick


1 Answers

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.

like image 160
Ionuț G. Stan Avatar answered Dec 21 '25 22:12

Ionuț G. Stan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!