From: chr_news@... (Chistoph) Date: 2001-11-04T03:30:21+09:00 Subject: [ruby-talk:24278] Re: examples of functional programming in Ruby ptkwt@shell1.aracnet.com (Phil Tomson) wrote in message news:<4hME7.93667$HZ.3157029@sjcpnn01.usenetserver.com>... > Would anyone be willing to share some code snippets that show examples of > functional programming in Ruby? > > Phil Hi, I have been absent from the ruby group for a while. Anyway here is an Fibbonacci example from the ``what if Fixnum singleton classes existed'' department. Surprisingly enough the implementation is faster then a straightforward recursive implementation. class Integer def fib return 1 if self < 2 return (self-1).fib + (self-2).fib end end (using generators is much faster but this another matter) ------------- require 'simple_rec.rb' class PositiveRecursiveInteger def fib; pred.fib + pred.pred.fib end def Null.fib; 1 end def (Null.succ).fib; 1 end end p (31.to_posrec_int.fib) ==> # 2178309 ------------- # simple_rec.rb # A simple example of a class with recursive # instance creation - not thread safe! class Module public :remove_method end class Object def remove_singleton_method sym class << self; self end.remove_method sym end end class PositiveRecursiveInteger < Numeric Null = self::new def Null.pred; raise ArgumentError 'negative predessor' end def Null.succ; __succ__ end Null.instance_eval { @to_i = 0 } attr_reader :succ, :pred, :to_i def to_s; @to_i.to_s end alias inspect to_s def initialize p; @pred = p end private def __succ__ remove_singleton_method :succ @succ = PositiveRecursiveInteger::new self def @succ.succ; __succ__ end return @succ end public def coerce (other); [to_i, other] end def +(other); to_i + other end def -(other); to_i - other end def *(other); to_i* other end # etc ... end class Fixnum # this is rather slow .. def to_posrec_int raise ArgumentError 'negative argument' if self < 0 res = PositiveRecursiveInteger::Null times { res=res.succ } return res end end