Version française
Home     About     Download     Resources     Contact us    
Browse thread
Question on Variant Types
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jonathan Roewen <jonathan.roewen@g...>
Subject: Re: Another question on variant types and matching (was: Re: [Caml-list] Question on Variant Types)
Hi,

You just need some type constraints so it knows you're starting with a
colour pair, not a colour' pair:

let process_instructions (initial:colour * colour) =
 List.fold_left (
   fun (fg, bg) ->
     function
     | Set_foreground `Default ->
         let new_fg = default_fg in
         (new_fg, bg)
     | Set_foreground (#colour as new_fg) ->
         (new_fg, bg)
     | Set_background `Default ->
         let new_bg = default_bg in
         (fg, new_bg)
     | Set_background (#colour as new_bg) ->
         (fg, new_bg)
 ) initial

Jonathan

On 6/30/06, Richard Jones <rich@annexia.org> wrote:
> I have another question on variant types which seems to be related to
> this, but perhaps the opposite way round.  How can I get the code
> below to work?  (It's simplified greatly from a real problem I'm
> having).
>
> Rich.
>
> ----------------------------------------------------------------------
> type colour = [ `Red | `Green | `Blue ]
> type colour' = [ colour | `Default ]
> type instructions = Set_foreground of colour' | Set_background of colour'
>
> let default_fg : colour = `Red
> let default_bg : colour = `Green
>
> let process_instructions =
>  List.fold_left (
>    fun (fg, bg) ->
>      function
>      | Set_foreground `Default ->
>          let new_fg = default_fg in
>          (new_fg, bg)
>      | Set_foreground new_fg ->
>          (new_fg, bg)
>      | Set_background `Default ->
>          let new_bg = default_bg in
>          (fg, new_bg)
>      | Set_background new_bg ->
>          (fg, new_bg)
>  )
>
> let string_of_colour = function
>  | `Red -> "red"
>  | `Green -> "green"
>  | `Blue -> "blue"
>
> let () =
>  let instrs =
>    [ Set_foreground `Blue; Set_background `Red; Set_foreground `Default ] in
>  let fg, bg = `Green, `Blue in
>  let fg, bg = process_instructions (fg, bg) instrs in
>  print_endline ("fg = " ^ string_of_colour fg);
>  print_endline ("bg = " ^ string_of_colour bg)
> ----------------------------------------------------------------------
>
> --
> Richard Jones, CTO Merjis Ltd.
> Merjis - web marketing and technology - http://merjis.com
> Team Notepad - intranets and extranets for business - http://team-notepad.com
>
> _______________________________________________
> Caml-list mailing list. Subscription management:
> http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
> Archives: http://caml.inria.fr
> Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
> Bug reports: http://caml.inria.fr/bin/caml-bugs
>