Patterns
Strategy #
A rule is an Fn value: pass a function with &name or a block.
def total(prices: List[Int], discount: Fn[Int, Int]) -> Int
prices.reduce(0) do |sum, price| sum + discount.call(price) end
end
def half(price: Int) -> Int = price / 2
def main() -> Void
puts(total([100, 50], &half))
puts(total([100, 50]) do |price| price - 10 end)
endOutput
75
130Factory #
One function builds a value from a name and returns a Result[T].
enum Shape
Circle(Float)
Square(Float)
end
def shape(kind: String, size: Float) -> Result[Shape]
case kind
"circle" -> ok(Shape.Circle(size))
"square" -> ok(Shape.Square(size))
_ -> error("unknown shape: #{kind}")
end
end
def main() -> Void
puts(shape("square", 3.0).unwrap!)
puts(shape("star", 1.0).message)
endOutput
Shape.Square(3.0)
unknown shape: starBuilder #
Give struct fields defaults, then change some with with.
struct Request
url: String
method: String = "GET"
retries: Int = 0
end
def main() -> Void
request = Request(url: "https://example.com").with(method: "POST").with(retries: 3)
puts("#{request.method} #{request.retries}")
endOutput
POST 3State machine #
An enum is the state and a case is the step.
enum Door
Open
Closed
end
enum Event
Push
Pull
end
def step(door: Door, event: Event) -> Door
case door
Door.Open ->
case event
Event.Push -> Door.Closed
_ -> door
end
Door.Closed ->
case event
Event.Pull -> Door.Open
_ -> door
end
end
end
def main() -> Void
puts([Event.Push, Event.Push, Event.Pull].reduce(Door.Open) do |state, event| step(state, event) end)
endOutput
Door.OpenCommand #
Actions are enum variants; one function applies them.
enum Command
Deposit(Int)
Withdraw(Int)
end
def apply(balance: Int, command: Command) -> Int
case command
Command.Deposit(n) -> balance + n
Command.Withdraw(n) -> balance - n
end
end
def main() -> Void
puts([Command.Deposit(100), Command.Withdraw(30)].reduce(0) do |balance, command| apply(balance, command) end)
endOutput
70Decorator #
A function takes an Fn and returns a new one, a lambda that calls it.
def logged(f: Fn[Int, Int]) -> Fn[Int, Int]
->(x) {
y = f.call(x)
puts("f(#{x}) = #{y}")
y
}
end
def main() -> Void
double = logged do |x| x * 2 end
double.call(4)
endOutput
f(4) = 8Observer #
The subject holds a list of Fn.
struct Bus
handlers: List[Fn[String, String]]
end
def subscribe(bus: Bus, handler: Fn[String, String]) -> Bus = bus.with(handlers: bus.handlers.push(handler))
def publish(bus: Bus, message: String) -> List[String] = bus.handlers.map do |handler| handler.call(message) end
def shout(text: String) -> String = text.upcase
def main() -> Void
puts(Bus(handlers: []) |> subscribe(&shout) |> publish("hello"))
endOutput
["HELLO"]