Created
April 26, 2011 06:18
-
-
Save mneedham/941867 to your computer and use it in GitHub Desktop.
Purely Functional Data Structures - Chris Okasaki
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Write a function suffixes of type that takes a list xs & returns a list of all the suffixes of xs in decreasing order of length | |
For example: | |
suffixes [1, 2, 3, 4] => [[1, 2, 3, 4], [2, 3, 4], [3, 4], [4], []] | |
Non tail recursive: | |
let rec suffixes list = | |
match list with | |
| [] -> [[]] | |
| hd::tl -> list :: (suffixes tl) | |
Tail recursive: | |
Following Brian McNamara's post - http://cs.hubfs.net/forums/permalink/8022/8022/ShowThread.aspx#8022 | |
let suffixesTR list = | |
let rec loop l acc = | |
match l with | |
| [] -> acc | |
| [last] -> loop [] ([] :: ([last] :: acc)) | |
| hd::tl -> loop tl (l :: acc) | |
in | |
loop list [] |> List.rev | |
Is there any way to do the tail recursive one without using List.rev cause that seems pretty lame! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment