0hc.net Menu
Home Overview
About Menu
Impressum

Array

Some useful definitions: class Array def ddup y=[]; self.each{|z| if z.class==Array then y+=[z.ddup] else y+=[z] end} return y end def tail self[1,self.length-1] end def foldr(f,z) x=self.length return z if x==0 f.call(self.first,self[1,x-1].foldr(f,z)) end def foldl(f,z) x=self.length return z if x==0 self[1,x-1].foldl(f,f.call(z,self.first)) end end Here is a program to evaluate a polynomial function of any order: puts lambda{|xs| xs.tail.foldr(lambda{|s,t| s+t*xs.first},0)}.call(gets.split.map!{|x|x.to_f}) And my original version in Haskell: main = getLine >>= \li -> (\(x:xs) -> print (foldr (\s t -> s+x*t) 0 xs)) (map read (words li)) To see how foldr and foldl work: a=[2,3,2] puts a.foldr(lambda{|i,j| i-j},0) # (2-(3-(2-0))) = +1 puts a.foldl(lambda{|i,j| i-j},0) # (((0-2)-3)-2) = -7 print a, "\n" And ddup: a=[[1,1],[2,2]] b=a.dup b[0][0]=2 print a, "\n", b, "\n" # 2122 2122 a=[[1,1],[2,2]] b=a.ddup b[0][0]=2 print a, "\n", b, "\n" # 1122 2122
0hc.net    © 2001-2014 Harald Wolfsgruber