diff -r 114a89518aea -r 4383809c176a progs/lecture3.scala --- a/progs/lecture3.scala Tue Nov 21 16:31:11 2017 +0000 +++ b/progs/lecture3.scala Thu Nov 23 10:56:47 2017 +0000 @@ -51,22 +51,41 @@ -// One of only two places where I conceded to mutable -// data structures: The following function generates -// new labels +// Roman Numerals +abstract class RomanDigit +case object I extends RomanDigit +case object V extends RomanDigit +case object X extends RomanDigit +case object L extends RomanDigit +case object C extends RomanDigit +case object D extends RomanDigit +case object M extends RomanDigit + +type RomanNumeral = List[RomanDigit] -var counter = -1 - -def fresh(x: String) = { - counter += 1 - x ++ "_" ++ counter.toString() +def RomanNumeral2Int(rs: RomanNumeral): Int = rs match { + case Nil => 0 + case M::r => 1000 + RomanNumeral2Int(r) + case C::M::r => 900 + RomanNumeral2Int(r) + case D::r => 500 + RomanNumeral2Int(r) + case C::D::r => 400 + RomanNumeral2Int(r) + case C::r => 100 + RomanNumeral2Int(r) + case X::C::r => 90 + RomanNumeral2Int(r) + case L::r => 50 + RomanNumeral2Int(r) + case X::L::r => 40 + RomanNumeral2Int(r) + case X::r => 10 + RomanNumeral2Int(r) + case I::X::r => 9 + RomanNumeral2Int(r) + case V::r => 5 + RomanNumeral2Int(r) + case I::V::r => 4 + RomanNumeral2Int(r) + case I::r => 1 + RomanNumeral2Int(r) } -fresh("x") -fresh("x") - -// this can be avoided, but would have made my code more -// complicated +RomanNumeral2Int(List(I,I,I,I)) // 4 (invalid roman number) +RomanNumeral2Int(List(I,V)) // 4 +RomanNumeral2Int(List(V,I)) // 6 +RomanNumeral2Int(List(I,X)) // 9 +RomanNumeral2Int(List(M,C,M,L,X,X,I,X)) // 1979 +RomanNumeral2Int(List(M,M,X,V,I,I)) // 2017 // Tail recursion @@ -301,11 +320,15 @@ def ~ (r: String) = SEQ(s, r) } +//example regular expressions val digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" val sign = "+" | "-" | "" val number = sign ~ digit ~ digit.% +//implement print_re + + // Lazyness with style //=====================