[英]Haskell Perform Arithmetic Operations on Ints and Double
I've recently been writing an interpreter for a basic programming language and everything has gone ok. 我最近一直在为一种基本的编程语言编写解释器,一切正常。 However can someone advise me on the best approach to add support for doubles. 但是有人可以建议我增加对双打的支持的最佳方法。 Currently only Ints are supported but I would like to add support for Doubles too. 目前仅支持Ints,但我也想添加对Doubles的支持。
type Env a = [[Var, a]] 输入Env a = [[Var,a]]
This is a family of types. 这是一类类型。 Env Int
is an int environment, Env Double
is a double environment, and so on. Env Int
是int环境, Env Double
是双重环境,依此类推。 This is not a type that can hold both ints and doubles, which is probably what you need. 这不是可以同时容纳int和double的类型,这可能是您需要的。
A type that can hold both integers and doubles may look like this: 可以同时容纳整数和双精度的类型可能如下所示:
data Val = IntNum Int | DoubleNum Double
and then you can have your environment as 然后你就可以拥有你的环境
type Env = [ (Var, Val) ]
(I don't know why you are using a list of lists here). (我不知道您为什么在这里使用列表列表)。
You need to define arithmetic operations separately for IntNum
and DoubleNum
cases (and perhaps for mixed operands too if your language supports that). 您需要为IntNum
和DoubleNum
情况分别定义算术运算(如果您的语言支持,也可能要为混合操作数定义)。
Adding booleans and lists is straightforward, just add another couple of cases to Val
. 添加布尔值和列表很简单,只需在Val
再添加几个案例即可。
You will have to deal with type errors that will arise in your language as it begins to support more than one type. 当您的语言开始支持多种类型的语言时,您将不得不处理其语言中会出现的类型错误。 I don't think this simple design is well suited for a statically type-safe language. 我认为这种简单的设计不适用于静态类型安全的语言。 If you want that, the design has to be adapted significantly. 如果需要,必须对设计进行重大调整。
The simple answer would be to define an variant type that can hold ether Int
s or Double
s, eg 简单的答案是定义一个可以容纳ether Int
或Double
的变量类型,例如
data Value = Int Int
| Double Double
and modify the definition of Env
and other types correspondingly: 并相应地修改Env
和其他类型的定义:
type Env = [[(Var, Value)]]
data ValExpr = IVar Var
| IVal Value
...
But if you plan on adding more types, I would consider using GADT s. 但是,如果您打算添加更多类型,则可以考虑使用GADT 。
EDIT: typo 编辑:错别字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.