|
| 1 | +import Data.Ratio |
| 2 | +import Data.List |
| 3 | + |
| 4 | +data Digit = Neg |
| 5 | + | Zero |
| 6 | + | One |
| 7 | + | Two |
| 8 | + | Three |
| 9 | + | Four |
| 10 | + | Five |
| 11 | + | Six |
| 12 | + | Seven |
| 13 | + | Eight |
| 14 | + | Nine |
| 15 | + deriving (Show, Eq, Ord, Enum) |
| 16 | + |
| 17 | +instance Num Digit where |
| 18 | + fromInteger x |
| 19 | + | x == 0 = Zero |
| 20 | + | x >= 1 && x <= 9 = succ $ fromInteger (x-1) |
| 21 | + (+) x y = fromInteger (s `mod` 10) |
| 22 | + where s = toInteger x + toInteger y |
| 23 | + (-) x y = fromInteger (r `mod` 10) |
| 24 | + where r = toInteger x - toInteger y |
| 25 | + (*) x y = fromInteger (p `mod` 10) |
| 26 | + where p = toInteger x * toInteger y |
| 27 | + abs = id |
| 28 | + signum Zero = Zero |
| 29 | + signum _ = One |
| 30 | + |
| 31 | +instance Real Digit where |
| 32 | + toRational Zero = 0 % 1 |
| 33 | + toRational x = 1 + toRational (pred x) |
| 34 | + |
| 35 | +instance Integral Digit where |
| 36 | + toInteger Zero = 0 |
| 37 | + toInteger x = 1 + toInteger (pred x) |
| 38 | + quotRem x y = (fromInteger a, fromInteger b) |
| 39 | + where (a, b) = quotRem (toInteger x) (toInteger y) |
| 40 | + |
| 41 | +carryOrLend :: (Integer -> Integer -> Integer) -> Digit -> Digit -> Integer |
| 42 | +carryOrLend f x y |
| 43 | + | result < 0 = -1 |
| 44 | + | result >= 10 = quot result 10 |
| 45 | + | otherwise = 0 |
| 46 | + where result = f (toInteger x) (toInteger y) |
| 47 | + |
| 48 | + |
| 49 | +join :: [a] -> [[a]] -> [a] |
| 50 | +join _ [] = [] |
| 51 | +join xs xss = foldl1 joinNew xss |
| 52 | + where joinNew acc ys = acc ++ xs ++ ys |
| 53 | + |
| 54 | +data Expr = Cst Int |
| 55 | + | Var |
| 56 | + | Add [Expr] |
| 57 | + | Mul [Expr] |
| 58 | +instance Show Expr where |
| 59 | + show (Cst c) = show c |
| 60 | + show Var = "x" |
| 61 | + show (Mul xs) = "(" ++ join "*" (map show xs) ++ ")" |
| 62 | + show (Add xs) = "(" ++ join "+" (map show xs) ++ ")" |
| 63 | +data Equal = Equal Expr Expr |
| 64 | + |
| 65 | +--normalize :: Expr -> Expr |
| 66 | +--normalize (Cst x) = Cst x |
| 67 | +--normalize Var = Var |
| 68 | +--normalize (Mul (Add x y) z) = Add (normalize (Mul x z)) (normalize (Mul y z)) |
| 69 | +--normalize (Mul z (Add x y)) = normalize (Mul (Add x y) z) |
| 70 | +--normalize (Mul (Cst x) (Cst y)) = Cst (x * y) |
| 71 | +--normalize (Mul x y) = Mul (normalize x) (normalize y) |
| 72 | +--normalize (Add x y) = Add (normalize x) (normalize y) |
| 73 | + |
| 74 | +{- |
| 75 | +normalize :: Expr -> Expr |
| 76 | +normalize (Add xs) = merge $ |
| 77 | +
|
| 78 | +testExpr = Mul [Add [Var, Cst 2], Add [Mul [Cst 2, Var], Cst 3]] |
| 79 | +
|
| 80 | +solve :: Equal -> Maybe Int |
| 81 | +solve (Equal (Cst _) (Cst _)) = Nothing |
| 82 | +solve (Equal (Cst c) all@_ ) = solve (Equal all (Cst c)) |
| 83 | +solve (Equal Var (Cst c)) = Just c |
| 84 | +-} |
| 85 | + |
0 commit comments