Created
February 29, 2012 14:38
-
-
Save felixrabe/1941252 to your computer and use it in GitHub Desktop.
truth.rb
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
#!/usr/bin/env ruby | |
class Object | |
def > other # implication operator: false > true == true | |
if self == true or self == false | |
!self or other | |
else | |
super | |
end | |
end | |
end | |
class FalseClass ; def to_01 ; "0" ; end ; end | |
class TrueClass ; def to_01 ; "1" ; end ; end | |
class TruthTable | |
attr_reader :map, :results | |
def initialize &block | |
raise ArgumentError, "block expected", caller unless block | |
raise ArgumentError, "block should not take arguments" if block.arity > 0 | |
@counter = 0 | |
@map = [] | |
@results = [] | |
until @counter == 2 ** @map.size | |
@results << instance_eval(&block) | |
@counter += 1 | |
end | |
end | |
def method_missing name | |
index = @map.index name | |
if index | |
mask = 2 ** index | |
@counter & mask != 0 | |
else | |
@map << name | |
false | |
end | |
end | |
end | |
def truth_table &block | |
truth_table = TruthTable.new &block | |
map = truth_table.map | |
results = truth_table.results | |
n = map.size | |
puts map.join " " | |
f = "%0#{n}b" | |
lines = [] | |
for i in 0...2**n | |
a_s = (f % i).reverse | |
a_a = a_s.split("").map{|c| c != "0"} | |
inputs = map.map(&:size).each_with_index.map{|s,i| "%-#{s}s" % a_a[i].to_01}.join " " | |
output = results[i].to_01 | |
lines << "#{inputs} => #{output}" | |
end | |
puts lines.sort | |
end | |
alias tt truth_table |
Implication: ruby -r ./truth.rb -e 'tt { this > that }'
Creating a “truth table” is not hard, you can use an useful tool (CKod, at http://ckod.sourceforge.net/_/) to make a “truth table”.
- CKod homepage: http://ckod.sourceforge.net/
- CKod online: http://ckod.sourceforge.net/_/
- CKod forum: http://ckod.sourceforge.net/~/
Good luck to you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
ruby -r ./truth.rb -e 'tt { a and not b }'