4
\$\begingroup\$

I wrote the following suffixes function. Given a list, it returns the list + all sub-lists.

suffixes [1,2,3,4] == [[1,2,3,4], [2,3,4], [3,4], [4], []]

Please critique my implementation.

suffixes :: [a] -> [[a]]
suffixes [] = [] : []
suffixes xxs@(_:xs) = xxs : suffixes xs
asked Oct 17, 2014 at 1:07
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

Looks good to me. The only thing I would change is

suffixes [] = [] : []

to

suffixes [] = [[]]

as it's a bit more readable.

When re-inventing functions, it can be instructive to look up their definition using Hoogle. Following the links, we find this definition in Data.List:

tails :: [a] -> [[a]]
tails xs = xs : case xs of
 [] -> []
 _ : xs' -> tails xs'
answered Oct 17, 2014 at 1:19
\$\endgroup\$
2
  • \$\begingroup\$ Thank you for your continued help on most/all of my recent questions. \$\endgroup\$ Commented Oct 17, 2014 at 1:21
  • \$\begingroup\$ @KevinMeredith my pleasure. I thoroughly enjoyed the previous one (Streams) in particular :) \$\endgroup\$ Commented Oct 17, 2014 at 1:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.