Answer:
Check the explanation
Explanation:
type RomanDigit = int
type RomanNumeral = RomanDigit list
type RomanDigit = I | V | X | L | C | D | M
type RomanNumeral = RomanNumeral of RomanDigit list
/// Converting a single RomanDigits to an integers here
let digitToInt =
function
| I -> 1
| V -> 5
| X -> 10
| L -> 50
| C -> 100
| D -> 500
| M -> 1000
// testing here
I |> digitToInt
V |> digitToInt
M |> digitToInt
let rec digitsToInt = function
// empty is notified by using 0
| [] -> 0
// special case when a smaller comes before larger
// convert both digits and add the difference to the sum
// Example: "IV" and "CM"
| smaller::larger::ns when smaller < larger -> (digitToInt larger - digitToInt smaller) + digitsToInt ns
// otherwise convert the digit and add to the sum
| digit::ns -> digitToInt digit + digitsToInt ns
// tests
[I;I;I;I] |> digitsToInt
[I;V] |> digitsToInt
[V;I] |> digitsToInt
[I;X] |> digitsToInt
[M;C;M;L;X;X;I;X] |> digitsToInt // that is 1979
[M;C;M;X;L;I;V] |> digitsToInt // that is 1944
/// converts a RomanNumeral to an integer
let toInt (RomanNumeral digits) = digitsToInt digits
// test
let x = RomanNumeral [I;I;I;I]
x |> toInt
let x = RomanNumeral [M;C;M;L;X;X;I;X]
x |> toInt