3

in OCaml

Objective Caml version 3.11.0

# let rec last l=
    match l with
    [] -> failwith("Empty list")
    |a::[] -> a
    |a::r -> last r;;
val last : 'a list -> 'a = <fun>
# last [];;
Exception: Failure "Empty list".

In F#

>let rec last l = 
    match l with
    [] -> failwith("Empty list")
    | a::[] -> a
    | a::r -> last r;;

val last : 'a list -> 'a

>last [];;
 last [];;
 ^^^^^^^

 stdin(8,1): error FS0030: Restriction de valeur....

>last ([]:int list);;

System.Exception: Empty list
   à FSI_0002.last[a](FSharpList`1 l)
   à <StartupCode$FSI_0003>.$FSI_0003.main@()
Arrêt en raison d'une erreur

What whould I do to be able to pass the empty list as argument without triggering a value restriction error ?

Johan Buret
  • 2,614
  • 24
  • 32
  • Possibly see also http://stackoverflow.com/questions/1131456/understanding-f-value-restriction-errors – Brian Jun 15 '11 at 17:32

2 Answers2

1

I think you're going to have to put a type annotation somewhere, either on the empty list (as you have) or on the result of the call to last: (last [] : int).

kvb
  • 54,864
  • 2
  • 91
  • 133
  • @Johan - Imagine that your first case returned `Unchecked.defaultof<_>` instead of throwing an exception. Then what would you expect `last []` to give you in the interpreter? – kvb Jun 15 '11 at 14:35
  • It would have given another type of exception ? Just guessing. – Johan Buret Jun 15 '11 at 14:58
  • At the time I write this ( 2011-06-16 ) there seems to be no better way. – Johan Buret Jun 16 '11 at 15:18
0

You can do

last<obj> []

But fsi will give you a slapped wrist because last never explicitly declare it's type parameter.

Massif
  • 4,327
  • 23
  • 25