Welcome to F#! Coming from C#, you'll just need a bit of time to get into the swing of things :).

For your question, the only different cases are "empty" and "head and tail". The empty case is easy, print done. The other case requires two statements. First, print the current element + delimiter. Then print the rest of the list. (Because there is a delimiter after every element, since the Done needs it before it.)

let rec PrintList = function
| [] -> printfn "Done"
| x::xs -> printf "%A " x; PrintList xs

If you had a more complicated scenario, say you wanted to produce output without a delimiter after the 3:
1;2;3
Done

You could write it like this:

let rec PrintList = function
| [] -> printfn "Done"
| x::[] -> printfn "%A" x; PrintList []
| x::xs -> printf "%A;" x; PrintList xs

(BTW, the function keyword is just short for declaring a parameter and matching it.)

Finally, you can look at using reduce to get the same thing as your first case:

> let listfmt xs = List.reduce_left (fun acc s -> acc + " " + s) (xs @ ["Done"]);;
val listfmt : string list -> string

> listfmt ["one"; "two"];;
val it : string = "one two Done"

Hope that helps,
-Michael

By on 3/21/2009 12:01 PM ()

These are FANTASTIC responses. I especially like that one calls its recursive method passing an empy list. I sure didn't see that!

THANKS!

By on 3/21/2009 10:23 PM ()

There are no special cases, if I understand the spec correctly:

1
2
3
4
5
6
7
8
9
10
11
12
let PrettyPrintList l =
    l |> List.iter (printf "%d ")
    printfn "Done"

PrettyPrintList []        
PrettyPrintList [1]        
PrettyPrintList [1;2]        
PrettyPrintList [1;2;3]        
//Done
//1 Done
//1 2 Done
//1 2 3 Done
By on 3/21/2009 12:01 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper