I am creating a tiny language in Haskell that can perform simple math equations. The set up looks like this:
data E = IntLit Int
| BoolLit Bool
| Plus E E
| Minus E E
| Multiplies E E
| Exponentiate E E
| Equals E E
deriving (Eq, Show)
I have all of these working, but now I need to define a function for E that preserves the truth value of the expression by taking logs to base 2 if it is possible. If it isn't possible, the program may abort (e.g., with a Non-exhaustive pattern exception).
log2Sim :: E -> E
An example of running this should look like
> log2Sim (IntLit 8)
IntLit 3
Do I need to add log2Sim E to the language defined or is there another way? I'm trying to define it like so:
log2Sim :: E -> E
log2Sim (Log a) = log2sim (eval a)
log2sim (IntLit x) = IntLit $ logBase 2 x
But this is definitely not correct.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…