log2Sim For a Tiny Language In Haskell

早过忘川 提交于 2019-12-25 18:57:17

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/35805098/log2sim-for-a-tiny-language-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!