# My own class of lists. # Note that these lists misbehave if you try to store nil in them; # specifically, lists which start with nil are treated as empty, # so everything following a nil in the list will be ignored. class MyList # Create readers for two fields, here and next. attr_reader :here attr_reader :next # Initialise a list as a singleton or an empty list. def initialize(val=nil) @here = val @next = nil return self end # Add a value to the beginning of a list # Note that we test if the head (@here) is tested against nil; # lists with a nil head are considered to be empty. def prepend(val) if @here != nil # Reproduce the current list, making it the new next list @next = self.clone() end @here = val return self end def catenate(l) if @here != nil and @next != nil # keep recursing until we reach the end of our list @next = @next.catenate(l) elsif @here != nil # at the end, attach a copy of l @next = l.clone() else # there is no list here; just copy l @here = l.here @next = l.next end return self end def to_s if @here and @next return @here.to_s + " :: " + @next.to_s elsif @here return @here.to_s + " :: eol" else return "eol" end end end # The list containing 1, prepended with 2, catenated with the list containing 3 # 2 ∷ 1 ∷ 3 ∷ eol puts ((MyList.new(1)).prepend(2)).catenate(MyList.new(3))