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) |