haskell 代码感觉很清楚。
reverse [] = []
reverse (x:xs) = reverse xs ++ [x]
def reverse(list)
if list.empty?
[]
else
x, *xs = *list
(reverse xs) << x
end
end
这样?
Ruby 的库
static VALUE
rb_ary_reverse_m(VALUE ary)
{
long len = RARRAY_LEN(ary);
VALUE dup = rb_ary_new2(len);
if (len > 0) {
VALUE *p1 = RARRAY_PTR(ary);
VALUE *p2 = RARRAY_PTR(dup) + len - 1;
do *p2-- = *p1++; while (--len > 0);
}
ARY_SET_LEN(dup, RARRAY_LEN(ary));
return dup;
}
来个 scala 的?似乎一下就显出类型推导的短了
def reverse[T](list: List[T]): List[T] = list match {
case Nil => Nil
case head :: tail => reverse(tail) :+ head
}
嗯,用 case 匹配的: 或者http://codepad.org/TES3Rb1Y
def matchlist(mdata, x, xs)
->list{
Array === list && ->list{
mdata[x], *mdata[xs] = list; mdata[x]
}.(list) ## 木有 >>=要手动传递真不爽……
}
end
def reverse list, mdata = {}; case list
when [] then []
when matchlist(mdata, :x, :xs) then reverse(mdata[:xs]) << mdata[:x]
end;end
p reverse [1,2,3,4,5]
这样 reverse list 可是相当的慢的
reverse xs = reverse' xs [] where
reverse' [] acc = acc
reverse' (x:xs) acc = reverse' xs (x:acc)