Evaluating this function:
val constantly = fn k => (fn a => k);
Yields this SML signature:
val constantly = fn : 'a -> 'b -> 'a
yet Harper's book says the function has this signature:
'a -> ('b -> 'a)My questions are
1. how does Harper's signature differ from the one given by SML?
2. how would the SML signature differ in meaning from this:
val constantly = fn : ('a -> 'b) -> 'a 3. Is it possible that the 'b in the SML signature could actually be the same type as 'a ? Is there something which restricts the type of the input to the function returned from constantly from being the same as it outputs?
---
sweeks speaks:
[12:15] <sweeks> 1. 'a -> 'b -> 'a is the same as 'a -> ('b -> 'a)
[12:17] <sweeks> 2. 'a -> ('b -> 'a) takes an argument of type 'a, while ('a -> 'b) -> 'a takes a function as an argument.
[12:18] <sweeks> 3. When instantiating a polymorphic function, different type variables can be instantiated with the same types.
two-step use of closure
I wanted to bind the closure to a variable and then get the result of calling the closure, but it was not so easy:
- val g = constantly 5.0;
stdIn:35.1-35.23 Warning: type vars not generalized because of
value restriction are instantiated to dummy types (X1,X2,...)
val g = fn : ?.X1 -> real
- g 50;
stdIn:36.1-36.5 Error: operator and operand don't agree [literal]
operator domain: ?.X1
operand: int
in expression:
g 50
- (g) 50;
stdIn:1.1-1.7 Error: operator and operand don't agree [literal]
operator domain: ?.X1
operand: int
in expression:
g 50
- but sweeks saved the day:
[12:38] <sweeks> True, but the type system requires a type to be chosen at the declaration of g. [12:39] <sweeks> You can work around this peculiarity with val g: 'a -> real = fn z => constantly 5.0 z [12:40] <metaperl> ok and when you provide arguments to constantly with a space in between, what does that mean? [12:40] <metaperl> e.g., val m = constantly 5.0 9; [12:41] <sweeks> As you said, the type of "constantly 5.0" is "ANY -> real", i.e. it is a function. [12:41] *** palomer (~palomer@MTL-ppp-147087.qc.sympatico.ca) joined [12:41] <sweeks> So, "constantly 5.0 9" applies that function. [12:43] <metaperl> you mean constantly 5.0 9 is the same as (constantly 5.0) 9 [12:43] <sweeks> yes [12:43] <metaperl> or perhaps ( (constantly 5.0) 9) [12:43] <metaperl> both work? [12:43] <sweeks> yes
