Ruby ruby 能否像 haskell 一样实现 reverse

chenge · 2013年05月08日 · 最后由 doitian 回复于 2013年05月17日 · 3484 次阅读

haskell 代码感觉很清楚。

reverse [] = []
reverse (x:xs) = reverse xs ++ [x]

先介绍一下呗,不熟悉 haskell 看不懂这个。

def reverse(list)
  if list.empty?
    []
  else
    x, *xs = *list
    (reverse xs) << x
  end
end

这样?

#1 楼 @zgm

def reverse a 
    return [] if a==[]
    first,*rest = *a
    reverse(rest).push(first)
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;
}

#3 楼 @chenge B 大所说的高贵的 pattern match ruby 怕是没有,把你的例子改成 case 便比较像

erlang 酱油版

reverse([]) -> [];
reverse([H|T]) -> reverse(T) ++ [H]. 

来个 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)
需要 登录 后方可回复, 如果你还没有账号请 注册新账号