Fun Friday – Diamonds are Forever

Sometimes you write code you’re just not super happy with.

The Diamond Kata is a simple kata to take a single character parameter, and return a “diamond” shaped string.  Examples:

diamond 'A';; 
val it : string = "A"

diamond 'B';;
val it : string = "
 A 
B B
 A "

diamond 'C';;
val it : string = "
  A  
 B B 
C   C
 B B 
  A  "

etc;;

That’s how I describe this Kata I was working on. I’m just not super happy with it. It feels wordy, and a bit inelegant. Still, it does work (as long as you pass a character ‘greater’ than upper case A. I should probably enforce that sometime… but for now, here it is.

open System
let diamond char =
let chars = [ 'A' .. char ]
let numberOfChars = List.length chars
let padCount i = numberOfChars (i + 1)
let gridWidth = numberOfChars * 2 1
let pad i = new string (' ', i)
let init = chars |> List.mapi (fun i c> (string c), (padCount i))
let all = init @ (List.tail (List.rev init))
let makeLine (str,padCount) =
match gridWidth (padCount * 2 + 1) with
| 0 -> pad padCount + str + pad padCount
| a -> pad padCount + str + pad (a 1) + str + pad padCount
all |> List.map makeLine
|> List.reduce (fun x y> sprintf "%s%s%s" x Environment.NewLine y)

view raw
Diamond.fsx
hosted with ❤ by GitHub

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s