最初的回答肯定是好的,这里有另一个例子,假设您有一种带有某些操作的数据类型:
data Form = Square Int | Rectangle Int Int | EqTriangle Int
perimeter :: Form -> Int
perimeter (Square s) = s * 4
perimeter (Rectangle b h) = (b * h) * 2
perimeter (EqTriangle s) = s * 3
area :: Form -> Int
area (Square s) = s ^ 2
area (Rectangle b h) = (b * h)
area (EqTriangle s) = (s ^ 2) `div` 2
最初的回答:现在想象一下你添加了一个圆形:
现在假设你添加了一个圆形:
data Form = Square Int | Rectangle Int Int | EqTriangle Int | Cicle Int
add its operations:
perimeter (Cicle r ) = pi * 2 * r
area (Cicle r) = pi * r ^ 2
这个不太好,对吧?现在我想使用浮点型...那我得将每个整数改成浮点型。
最初的回答:这不是很好,对吧?现在我想要使用浮点数... 我需要将每个整数都改成浮点数。
data Form = Square Double | Rectangle Double Double | EqTriangle Double | Cicle Double
area :: Form -> Double
perimeter :: Form -> Double
"最初的回答" 只是原始的答案,但是,如果为了清晰和重复使用,我使用类型(type)会怎么样呢?
data Form = Square Side | Rectangle Side Side | EqTriangle Side | Cicle Radius
type Distance = Int
type Side = Distance
type Radius = Distance
type Area = Distance
perimeter :: Form -> Distance
perimeter (Square s) = s * 4
perimeter (Rectangle b h) = (b * h) * 2
perimeter (EqTriangle s) = s * 3
perimeter (Cicle r ) = pi * 2 * r
area :: Form -> Area
area (Square s) = s * s
area (Rectangle b h) = (b * h)
area (EqTriangle s) = (s * 2) / 2
area (Cicle r) = pi * r * r
那让我只需更改代码中的一行即可更改类型,比如我想要距离是整数类型,我只需要更改那一行。最初的回答。
perimeter :: Form -> Distance
...
totalDistance :: [Form] -> Distance
totalDistance = foldr (\x rs -> perimeter x + rs) 0
我希望结果为浮点数,所以我只需要更改以下代码:
Original Answer
type Distance = Float
如果我想将它更改为Int,我必须在函数中进行一些调整,但这是另一个问题。"最初的回答"