New comment on block [block-idm181614017232] #2582

Open
izderadicka opened this Issue May 18, 2014 · 0 comments

Projects

None yet

1 participant

@izderadicka

It'll be useful to more explain this:

fold method of instance s of stack (created as new stack []) has signature:

s#fold;;

  • : ('_a -> '_b -> '_a) -> '_a -> '_a =

when something is pushed into so '_a ('b in class definition) looks like weakly polymorphic. But it work normally like polymorphic type - I can do:

List.iter ~f: (fun x -> s#push x) [1;2;3;4];;

  • : unit = ()

    let all = s#fold (fun acc x -> x::acc) [];;

    val all : int list = [1; 2; 3; 4]

    let all = s#fold (fun acc x -> x+acc) 0;;

    val all : int = 10

and fold '_a is still not resolved:

s#fold;;

  • : ('_a -> int -> '_a) -> '_a -> '_a =

What trick is there?

If 'b will be declared in class definition and then used in method defintion like this:
class ['a,'b] stack init = object
....
method fold f (init:'b) = ....

then it creates truly weakly polymorphic type - after first call to fold '_a is resolved to type of init parameter:

let all = s#fold (fun acc x -> x::acc) [];;

val all : int list = [1; 2; 3; 4]

let all = s#fold (fun acc x -> x+acc) 0;;

Error: This expression has type int list but an expression was expected of type int

s#fold;;

  • : (int list -> int -> int list) -> int list -> int list =
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment