2 people like it.

Lippert's Comma Challenge Revisited

Stumbled upon this challenge and tried my hand: http://themechanicalbride.blogspot.com/2009/04/f-solution-to-eric-lippert-challenge.html The original challenge calls for a string result, so there's no issue with converting the sequence to a list from the outset since we need to enumerate it completely anyway; had it insisted on returning a sequence my answer would be different. > commaize ["ABC"; "DEF"; "G"; "H"];; val it : string = "ABC, DEF, G and H"

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
    let commaize s =
        let rec insert_commas list = 
            match List.length list with
            | 0 -> []
            | 1 -> list
            | 2 -> list.Head :: " and " :: list.Tail
            | _ -> list.Head :: ", " :: insert_commas list.Tail

        String.concat "" (Seq.toList s |> insert_commas ) 
val commaize : s:seq<string> -> string

Full name: Script.commaize
val s : seq<string>
val insert_commas : (string list -> string list)
Multiple items
val list : string list

--------------------
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val length : list:'T list -> int

Full name: Microsoft.FSharp.Collections.List.length
property List.Head: string
property List.Tail: string list
module String

from Microsoft.FSharp.Core
val concat : sep:string -> strings:seq<string> -> string

Full name: Microsoft.FSharp.Core.String.concat
module Seq

from Microsoft.FSharp.Collections
val toList : source:seq<'T> -> 'T list

Full name: Microsoft.FSharp.Collections.Seq.toList
Raw view Test code New version

More information

Link:http://fssnip.net/t6
Posted:9 years ago
Author:Hugh Gleaves
Tags: challenge , lippert , comma , string , concatenate