86.6k views
3 votes
Define a romanNumberToInt function that converts a RomanNumber value, which is a list of Roman digits, into an integer. Hints: - Assume the Roman number representation is valid. - Use recursion to sum up number in romanNumber because it is a list. - Use pattern guards to manage case when digits come in reverse order, e.g. IX, IV.

User Hovado
by
4.1k points

1 Answer

1 vote

Answer:

Check the explanation

Step-by-step 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

User Klubi
by
3.8k points