Skip to content

Instantly share code, notes, and snippets.

@solson
Created September 27, 2009 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solson/194556 to your computer and use it in GitHub Desktop.
Save solson/194556 to your computer and use it in GitHub Desktop.
Haskell/Functional programming in Ruby! Version 2012
#!/usr/bin/env ruby
# encoding: utf-8
## Haskell/Functional Programming in Ruby! Version 2012
## By Scott Olson
def λ(&block)
lambda(&block).curry
end
## The most basic function - returns its argument
id = λ {|a| a }
## General math functions
plus = λ {|a, b| a + b }
minus = λ {|a, b| a - b }
mult = λ {|a, b| a * b }
div = λ {|a, b| a / b }
mod = λ {|a, b| a % b }
## Equality functions
eq = λ {|x, y| x == y }
gt = λ {|x, y| x > y }
gte = λ {|x, y| x >= y }
lt = λ {|x, y| x < y }
lte = λ {|x, y| x <= y }
neq = λ {|x, y| x != y }
# These are flawed, their second arguments will be evaluated because they are function arguments.
andand = λ {|x, y| x && y }
oror = λ {|x, y| x || y }
not_ = λ {|x| not x }
## Some higher order functions
# flip flips a function's argument order
flip = λ {|f, x, y| f.(y).(x) }
# apply simply passes it's second function to it's first (Haskell's ($) operator)
apply = λ {|f, x| f.(x) }
# function composition
compose = λ {|f, g, x| f.(g.(x)) }
## List functions
head = λ {|xs| xs.first }
tail = λ {|xs| xs[1..-1] }
init = λ {|xs| xs[0..-2] }
last = λ {|xs| xs.last }
append = λ {|xs, ys| xs + ys }
null = λ {|xs| xs.empty? }
length = λ {|xs| xs.length }
reverse = λ {|xs| xs.reverse }
map = λ {|f, xs| xs.map{|x| f.(x) } }
filter = λ {|p, xs| xs.select{|x| p.(x) } }
## All the following code is so we can drop into irb and play around with these functions
require 'irb'
module IRB # :nodoc:
def self.start_session(binding)
unless @__initialized
args = ARGV
ARGV.replace(ARGV.dup)
IRB.setup(nil)
ARGV.replace(args)
@__initialized = true
end
workspace = WorkSpace.new(binding)
irb = Irb.new(workspace)
@CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
@CONF[:MAIN_CONTEXT] = irb.context
catch(:IRB_EXIT) do
irb.eval_input
end
end
end
IRB.start_session(binding)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment