Corey Tyrrell
Corey Tyrrell

Reputation: 11

Using foldr to return the suffixes of a list

I need to return the suffix of a list and can't seem to solve it.

Given a list [1,2,3], the function should return [[3],[2,3],[1,2,3]]. We're supposed to solve using foldr and an auxiliary function.

Upvotes: 1

Views: 928

Answers (3)

KeLaS
KeLaS

Reputation: 11

How about this:

[1,2,3,4] will return [[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] will return [[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]

Upvotes: 1

pad
pad

Reputation: 41290

Here is @Landei's solution in SML syntax:

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

I assume that you're allowed to use rev function from SML Basis Library. Otherwise, implementing such a function should be easy.

Upvotes: 1

Landei
Landei

Reputation: 54584

Haskell would be:

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

I don't know SML, but the solution should be similar

Upvotes: 0

Related Questions