# $Id: methcall.pliant,v 1.0 2002/02/07 16:39:00 dada Exp $
# http://dada.perl.it/shootout/
# (based on methcall.pliant by pixel@mandrakesoft)

module "/pliant/language/context.pli"
module "/pliant/language/compiler.pli"

meta inherit e
  if e:size<>1
    return
  var Pointer:Type interface :> (e:0 constant Type) map Type
  if addressof:interface=null
    return
  var Pointer:Arrow c :> e:module first "pliant type"
  if c=null or entry_type:c<>Type
    return
  var Pointer:Type implementation :> c map Type
  if interface:nb_fields<>0 and implementation:nb_fields<>0
    return
  for (var Int i) 0 interface:nb_fields-1
    var Pointer:TypeField f :> interface field i
    implementation define_field f:type f:name f:initial_value
  interface maybe implementation
  e set_void_result


type Toggle
  field Bool state

function init t start_state
  arg_w Toggle t ; arg Bool start_state
  t:state := start_state

method t value -> r
  arg Toggle t ; arg Bool r
  return t:state

method t activate -> r
  arg_rw Toggle t ; arg Toggle r
  t:state := not t:state
  return t

type NthToggle
  inherit Toggle
  field Int count_max
  field Int counter

function init t start_state max_counter
  arg_w NthToggle t ; arg Bool start_state ; arg Int max_counter
  init t start_state
  t:count_max := max_counter
  t:counter := 0

method t activate -> r
  arg_rw NthToggle t ; arg NthToggle r
  t:counter += 1
  if t:counter >= t:count_max
    t:state := not t:state;
    t:counter := 0;
  return t


function doit n
  arg Int n
  var Toggle toggle
  var Bool val := true

  for (var Int i) 1 n
    val := toggle:activate:value
  console val eol

  val := true
  var NthToggle ntoggle
  init ntoggle val 3
  
  for (var Int i) 1 n
    val := ntoggle:activate:value
  console val eol


gvar Str s_n := cast ((pliant_script_args translate Address 1) map CStr) Str
if (s_n parse (gvar Int n))
  doit n
else
  console "usage: methcall.pliant <number>" eol