How to resolve the algorithm Roman numerals/Decode step by step in the F# programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Roman numerals/Decode step by step in the F# programming language

Table of Contents

Problem Statement

Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Roman numerals/Decode step by step in the F# programming language

Source code in the fsharp programming language

let decimal_of_roman roman =
    let rec convert arabic lastval = function
        | head::tail ->
            let n = match head with
                    | 'M' | 'm' -> 1000
                    | 'D' | 'd' -> 500
                    | 'C' | 'c' -> 100
                    | 'L' | 'l' -> 50
                    | 'X' | 'x' -> 10
                    | 'V' | 'v' -> 5
                    | 'I' | 'i' -> 1
                    | _ -> 0
            let op = if n > lastval then (-) else (+)
            convert (op arabic lastval) n tail
        | _ -> arabic + lastval
    convert 0 0 (Seq.toList roman)
;;


let decimal_of_roman roman =
    let convert (arabic,lastval) c =
        let n = match c with
                | 'M' | 'm' -> 1000
                | 'D' | 'd' -> 500
                | 'C' | 'c' -> 100
                | 'L' | 'l' -> 50
                | 'X' | 'x' -> 10
                | 'V' | 'v' -> 5
                | 'I' | 'i' -> 1
                | _ -> 0
        let op = if n > lastval then (-) else (+)
        (op arabic lastval, n)
    let (arabic, lastval) = Seq.fold convert (0,0) roman
    arabic + lastval
;;


let tests = ["MCMXC"; "MMVIII"; "MDCLXVII"; "MMMCLIX"; "MCMLXXVII"; "MMX"]
for test in tests do Printf.printf "%s: %d\n" test (decimal_of_roman test)
;;


  

You may also check:How to resolve the algorithm Dragon curve step by step in the F# programming language
You may also check:How to resolve the algorithm I before E except after C step by step in the Racket programming language
You may also check:How to resolve the algorithm Guess the number step by step in the jq programming language
You may also check:How to resolve the algorithm Continued fraction/Arithmetic/Construct from rational number step by step in the Mercury programming language
You may also check:How to resolve the algorithm Read a file line by line step by step in the PARI/GP programming language