Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

log2Sim For a Tiny Language In Haskell

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let's always eval to see if we get an IntLit

Something like (not typechecked...)

log2Sim :: E -> E
log2sim x = case (eval x) of
    IntLit i -> IntLit (logBase 2 i)
    x1 -> error $ "type error: can't take the log of a non-IntLit-valued expression: " ++ show x1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...