add_four_to_digit = ("0" : "4") | ("1": "5") | ("2": "6") | ("3": "7") | ("4" : "8") | ("5" : "9") | ("6" : "0S") | ("7" : "1S") | ("8" : "2S") | ("9" : "3S"); digit_unchanged = "0" | "1" | "2" | "3" | "4" | ("5" : "5") | ("6" : "6") | ("7" : "7" ) | ("8" : "8") | ("9" : "9"); decimal = ("S0" : "1") | ("S1" : "2") | ("S2" : "3") | ("S3" : "4") | ("S4" : "5") | ("S5" : "6") | ("S6" : "7") | ("S7" : "8") | ("S8" : "9") | ("S9" : "0S"); number_unchanged = digit_unchanged+ ; add_four_simple = add_four_to_digit number_unchanged? ; s_is_one = "S" : "1"; handle_carry = CDRewrite[number_unchanged? decimal number_unchanged?, "", "", ("S" | number_unchanged)*]; check_s = CDRewrite[number_unchanged? s_is_one, "", "", ("S" | number_unchanged)*]; export PROCESS = Optimize[Reverse[add_four_simple @ handle_carry @ handle_carry @ handle_carry @ handle_carry @ check_s]];