Created
April 20, 2015 03:31
-
-
Save jremmen/77909aeef7b7e10fe0a9 to your computer and use it in GitHub Desktop.
Some random generators in ruby based on Coursera reactive programming course
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Generators | |
module Utils | |
def self.included(other) | |
other.extend(ModuleMethods) | |
end | |
module ModuleMethods | |
def arbitrary | |
@arbitrary ||= {}.tap do |o| | |
o[Integer] = ->{Random.rand(-1e+10..1e+10).to_i} | |
o[Boolean] = ->{o[Integer] > 0} | |
end | |
end | |
def integers | |
arbitrary[Integer].call | |
end | |
def booleans | |
arbitrary[Boolean].call | |
end | |
def choose(lo, hi) | |
lo + integers % (hi - lo) | |
end | |
def one_of(*xs) | |
xs[choose(0, xs.length)].call | |
end | |
class Boolean; end | |
end | |
end | |
module Arrays | |
include Utils | |
def self.generate | |
one_of(->{[]}, ->{generate.push(integers)}) | |
end | |
end | |
module Trees | |
include Utils | |
def self.generate | |
self.one_of(->{Leaf.new(integers)}, ->{Node.new(generate, generate)}) | |
end | |
class Leaf | |
def initialize(x) | |
@x = x | |
end | |
def to_s | |
"(#{@x})" | |
end | |
end | |
class Node | |
def initialize(l, r) | |
@l = l | |
@r = r | |
end | |
def to_s | |
"(#{@l} . #{@r})" | |
end | |
end | |
end | |
module Lists | |
include Utils | |
def self.generate | |
one_of(->{List.new(nil)}, ->{generate.cons(integers)}) | |
end | |
class List | |
attr_accessor :head, :tail | |
def initialize(*xs) | |
@head = xs.first | |
@tail = List.new(*xs[1..-1]) if xs.any? | |
end | |
def cons(x) | |
l = List.new(x) | |
l.tail = self | |
l | |
end | |
def to_s | |
"(#{@head} #{@tail})" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment