Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean when an OCaml variable starts with `#`? (hash sign/pound sign)?

I cam across this in a pattern match

| {call_name = #bundle_source; _ }

source

Earlier in the code, bundle_source is defined as a type (type bundle_source = ...).

So what does the hash sign mean? Does {call_name = #bundle_source } in the pattern match mean that the value of call_name is expected to have type bundle_source?

I searched the manual for "hash sign" and "pound sign" but found nothing.

like image 691
Max Heiber Avatar asked May 15 '17 22:05

Max Heiber


2 Answers

This is a shorthand for constructing patterns that match a collection of polymorphic variant values.

The documentation is in Section 6.6 of the OCaml manual:

If the type [('a,'b,…)] typeconstr = [ ` tag-name1 typexpr1 | … | ` tag-namen typexprn] is defined, then the pattern #typeconstr is a shorthand for the following or-pattern: ( `tag-name1(_ : typexpr1) | … | ` tag-namen(_ : typexprn)). It matches all values of type [< typeconstr ].

# type b = [`A | `B];;
type b = [ `A | `B ]
# let f x =
  match x with
  | #b -> "yes"
  | _ -> "no";;
val f : [> b ] -> string = <fun>
# f `A;;
- : string = "yes"
# f `Z;;
- : string = "no"

(I was not familiar with this notation either.)

like image 155
Jeffrey Scofield Avatar answered Oct 18 '22 19:10

Jeffrey Scofield


As a complement of the use of #typeconstr in patterns, in a type expression #class-path indicates a subtype of the class #class_path. For instance, with

class c = object method m = () end
class d = object inherit c method n = () end
let f (x:c) = ()
let g (x:#c) = ()

the call f (new d) fails with

Error: This expression has type d but an expression was expected of type c.
The second object type has no method n 

since f expects an object of type c exactly, whereas g (new d) is accepted by the type-checker since d is a a subclass of c (note that `g (object method m = () end) would also be accepted).

like image 36
octachron Avatar answered Oct 18 '22 20:10

octachron