Skip to content

Commit

Permalink
[gleam][roman-numerals] use case statement directly
Browse files Browse the repository at this point in the history
  • Loading branch information
joaofnds committed Mar 26, 2024
1 parent 95a2bb1 commit bba1e47
Showing 1 changed file with 16 additions and 22 deletions.
38 changes: 16 additions & 22 deletions gleam/roman-numerals/src/roman_numerals.gleam
Original file line number Diff line number Diff line change
@@ -1,28 +1,22 @@
import gleam/list

const value_to_roman = [
#(1000, "M"),
#(900, "CM"),
#(500, "D"),
#(400, "CD"),
#(100, "C"),
#(90, "XC"),
#(50, "L"),
#(40, "XL"),
#(10, "X"),
#(9, "IX"),
#(5, "V"),
#(4, "IV"),
#(1, "I"),
]

pub fn convert(number: Int) -> String {
convert_iter(number, "")
}

fn convert_iter(remainder: Int, result: String) -> String {
case list.find(value_to_roman, fn(pair) { remainder >= pair.0 }) {
Ok(#(value, roman)) -> convert_iter(remainder - value, result <> roman)
_ -> result
fn convert_iter(number: Int, roman: String) -> String {
case number {
_ if number >= 1000 -> convert_iter(number - 1000, roman <> "M")
_ if number >= 900 -> convert_iter(number - 900, roman <> "CM")
_ if number >= 500 -> convert_iter(number - 500, roman <> "D")
_ if number >= 400 -> convert_iter(number - 400, roman <> "CD")
_ if number >= 100 -> convert_iter(number - 100, roman <> "C")
_ if number >= 90 -> convert_iter(number - 90, roman <> "XC")
_ if number >= 50 -> convert_iter(number - 50, roman <> "L")
_ if number >= 40 -> convert_iter(number - 40, roman <> "XL")
_ if number >= 10 -> convert_iter(number - 10, roman <> "X")
_ if number >= 9 -> convert_iter(number - 9, roman <> "IX")
_ if number >= 5 -> convert_iter(number - 5, roman <> "V")
_ if number >= 4 -> convert_iter(number - 4, roman <> "IV")
_ if number >= 1 -> convert_iter(number - 1, roman <> "I")
_ -> roman
}
}

0 comments on commit bba1e47

Please sign in to comment.