Extending an existing type in OCaml

后端 未结 4 967
栀梦
栀梦 2020-12-10 01:43

I\'ve been doing some OCaml programming lately to learn the language and to get more acquainted with functional programming. Recently, I\'ve started to think that I\'d like

4条回答
  •  时光取名叫无心
    2020-12-10 02:04

    An interesting solution is to use polymorphic variant:

    type bexp =
    [ `And of bexp * bexp
    | `Or of bexp * bexp
    | `Xor of bexp * bexp
    | `Not of bexp ];;
    
    type nbexp = [ bexp | `Nop of nbexp ];;
    

    Note that polymorphic variants are trickier than normal ones, but allow extension of type.

    An interesting example of expression evaluation, with extension, using polymorphic variant can be found in a test directories of the ocaml source, see the svn

提交回复
热议问题