【问题标题】:Using foldr to return the suffixes of a list使用 foldr 返回列表的后缀
【发布时间】:2012-10-08 08:31:41
【问题描述】:

我需要返回一个列表的后缀,似乎无法解决。

给定一个列表[1,2,3],函数应该返回[[3],[2,3],[1,2,3]]。我们应该使用 foldr 和一个辅助函数来解决。

【问题讨论】:

  • 这样想:foldr 会以相反的顺序为您呈现输入列表的每一项,以及您到目前为止的累积结果。如果您有列表中第一个 n 后缀的列表和 n+1th 元素(从末尾数)来计算 n+1th 后缀,您需要做什么?

标签: sml smlnj fold


【解决方案1】:

这是@Landei 在 SML 语法中的解决方案:

fun suffixes xs = 
   let 
      fun f (y, []) = [[y]]
        | f (y, yss as (ys::_)) = (y::ys)::yss
   in
      rev (foldr f [] xs)
   end

我假设您可以使用SML Basis Library 中的rev 函数。否则,实现这样的功能应该很容易。

【讨论】:

    【解决方案2】:

    这个怎么样:

    [1,2,3,4] 将返回 [[1,2,3,4],[2,3,4],[3,4],[4]] :

    fun myfun1 l = foldr(fn (a,b)=> if a=nil then [] else a::b@myfun1(tl(l)))[] [l]
    

    [1,2,3,4] 将返回 [[4],[3,4],[2,3,4],[1,2,3,4]] :

    fun myfun2 l = foldr(fn (a,b)=> if a=nil then [] else myfun2(tl(l))@a::b)[] [l]
    

    【讨论】:

      【解决方案3】:

      Haskell 将是:

      suffixes = reverse . foldr f [] where
        f y [] = [[y]]
        f y (yss@(ys:_)) = (y:ys) : yss  
      

      我不知道SML,但解决方案应该类似

      【讨论】:

      • 我将您的函数翻译成 SML。希望你不要介意。
      • 谢谢!这确实非常相似(如果我也使用let 会更相似)。
      猜你喜欢
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多