Class: Ruff::Standard::State::Instance

Inherits:
Object
  • Object
show all
Defined in:
lib/ruff/standard/state.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeInstance

makes new instances.



29
30
31
32
33
34
35
# File 'lib/ruff/standard/state.rb', line 29

def initialize
  # delegates effect instances.
  @eff = OpenStruct.new(
    get: Ruff.instance,
    modify: Ruff.instance
  )
end

Instance Attribute Details

#effObject (readonly)

You can reimplement the handler using these effect instances with accessing #eff.get and #eff.modify .



101
102
103
# File 'lib/ruff/standard/state.rb', line 101

def eff
  @eff
end

Instance Method Details

#getS

is a smart method to invoke the effect operation State.get .

Returns:

  • (S)

    with with , returns S , the current state.



40
41
42
# File 'lib/ruff/standard/state.rb', line 40

def get
  @eff.get.perform
end

#modify(&fn) ⇒ ()

is a smart hetmod to invoke the effect operation State.modify .

Parameters:

  • fn (Proc<S, U>)

    is the function to modify the state S to U . This function has an argument receiving the state.

Returns:

  • (())


49
50
51
# File 'lib/ruff/standard/state.rb', line 49

def modify(&fn)
  @eff.modify.perform fn
end

#put(s) ⇒ ()

is a short hand for modify {|_| s }

Parameters:

  • s (S)

    is the new state.

Returns:

  • (())


57
58
59
# File 'lib/ruff/standard/state.rb', line 57

def put(s)
  @eff.modify.perform ->(_) { s }
end

#with(&th) ⇒ A!{e}

is a short hand for with_init(nil, th) .

Parameters:

  • th (Proc<(), A!{State.get, State.modify,, e}>)

    is a thunk returning A with the possibility to invoke effects, including State.get and State.modify .

Returns:

  • (A!{e})

    returns A , without modification by value handler. But it still has the possibility to invoke effects(e).



95
96
97
# File 'lib/ruff/standard/state.rb', line 95

def with(&th)
  with_init(nil, &th)
end

#with_init(init, &th) ⇒ A!{e}

is a handler to interpret the effect invocations like state monad .

Parameters:

  • init (S)

    is the initial state.

  • th (Proc<(), A!{State.get, State.modify,, e}>)

    is a thunk returning A with the possibility to invoke effects, including State.get and State.modify .

Returns:

  • (A!{e})

    returns A , without modification by value handler. But it still has the possibility to invoke effects(e).



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/ruff/standard/state.rb', line 71

def with_init(init, &th)
  # not a parameter passing style, or so-called *pure* implementation,
  # just using mutable assignment
  state = init

  # The handler *closes* `state` variable so it should be created every time.
  Ruff.handler
      .on(@eff.modify) do |k, fn|
    state = fn[state]
    k[nil]
  end.on(@eff.get) do |k|
    k[state]
  end
      .run(&th)
end