Curry in Ruby

Inspired by some currying examples in scheme, I wanted to try them in Ruby…

def seq(oldfirst, keepold)
  lambda do |new, old, item, list|
    list.push(new) if old==item and  !oldfirst
    list.push(item) if keepold or old != item
    list.push(new) if oldfirst and old==item
  end
end

def insertF(new, old, list, func)
  temp = []
  list.each do |item|
    func.call new, old, item, temp
  end
  return temp
end

def insertR(new,old,list)
  insertF(new,old,list, seq(true,true))
end

def insertL(new,old,list)
  insertF(new,old,list,seq(false,true))
end

def subst(new,old,list)
  insertF(new,old,list,seq(false,false))
end

#examples
insertL("z","b",["a","b","c"])
insertR("z","b",["a","b","c"])
subst("z","b",["a","b","c"])

Posted

in

,

by

Tags: