Are there ruby equivalents to car, cdr, and cons?

前端 未结 5 933
终归单人心
终归单人心 2021-02-05 05:35

Are there ruby equivalents to the lisp car, cdr, and cons functions? For those unfamiliar with lisp, here\'s what I want from ruby:

[1,2,3].car   => 1
[1,2,3]         


        
5条回答
  •  日久生厌
    2021-02-05 06:14

    Semi-seriously, if you want CONS, CAR, and CDR in Ruby, you could do worse than

    def cons(x,y)
       return lambda {|m| m.call(x,y)}
    end
    
    def car(z)
      z.call(lambda {|p,q| p})
    end
    
    def cdr(z)
      z.call(lambda {|p,q| q})
    end
    

    And then you can define your list procedures,

    def interval(low, high)
      if (low > high)
        return nil
      else
        return cons(low, interval(low + 1, high))
      end
    end
    
    def map(f, l)
      if (l == nil)
        return nil
      else
        cons(f.call(car(l)), map(f, cdr(l)))
      end
    end
    
    def filter(p, l)
      if (l == nil)
        return nil
      elsif (p.call(car(l)))
        return cons(car(l), filter(p, cdr(l)))
      else
        return filter(p, cdr(l))
      end
    end
    
    def reduce(f, f0, l)
      if (l == nil)
        return f0
      else
        return f.call(car(l), reduce(f, f0, cdr(l)))
      end
    end
    

    And then you might get the sum of the odd squares in the range 1 to 10:

    reduce(lambda {|x, y| x + y},
           0,
           filter(lambda {|x| x % 2 == 1},
                  map(lambda {|x| x * x},
                      interval(1, 10))))
    => 165
    

提交回复
热议问题