F#: String Calculator Kata

Intro

I am learning F# and am logging my progress or lack of. In doing so, I attempted a Kata for implementing a string calculator.

I did steps 1-4 of the exercise. I then got bored and decided to look for other katas.

The following code was generated to satisfy the guts of the kata:

module Calculator

open FsUnit
open NUnit.Framework
open System

let add (numbers:string) =

    let add (numbers:string) (delimiters) =
        if numbers.Length = 0 then 0
        else numbers.Split(delimiters) |> Array.map Int32.Parse
                                       |> Array.sum
    let delimiters = [|',';'\n'|]
    let tokens = numbers.Split(delimiters);
    let lastToken = tokens.[tokens.Length-1]

    let valid = lastToken <> ""
    if valid then add numbers delimiters
    else 0

Here’s the tests that flushed out the code:

[<Test>]
let ``adding empty string returns zero`` () =

    let result = add ""
    result |> should equal 0

[<Test>]
let ``adding one number returns number`` () =

    let result = add "3"
    result |> should equal 3

[<Test>]
let ``add two numbers`` () =

    let result = add "3,4"
    result |> should equal 7

[<Test>]
let ``add three numbers`` () =

    let result = add "3,4,5"
    result |> should equal 12

[<Test>]
let ``line feeds embedded`` () =

    let result = add "3\n4"
    result |> should equal 7

[<Test>]
let ``1,\n will not be processed`` () =

    let result = add "1\n"
    result |> should equal 0

Conclusion

In conclusion, I am learning F# and am logging my progress or lack of. In doing so, I attempted a Kata for implementing a string calculator.

I did steps 1-4 of the exercise. I then got bored and decided to look for other katas.

Leave a Reply

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: