F#具有度量单位功能,如http://msdn.microsoft.com/en-us/library/dd233243.aspx所述,如下所示:
[<Measure>] type unit-name [ = measure ]
Run Code Online (Sandbox Code Playgroud)
这允许定义单位,例如:
type [<Measure>] USD
type [<Measure>] EUR
Run Code Online (Sandbox Code Playgroud)
代码写成:
let dollars = 25.0<USD>
let euros = 25.0<EUR>
// Results in an error as the units differ
if dollars > euros then printfn "Greater!"
Run Code Online (Sandbox Code Playgroud)
它还处理转换(我猜这意味着Measure定义了一些函数,让Measures成倍增加,分割和取幂):
// Mass, grams.
[<Measure>] type g
// Mass, kilograms.
[<Measure>] type kg
let gramsPerKilogram: float<g kg^-1> = 1000.0<g/kg>
let convertGramsToKilograms (x: float<g>) = x / gramsPerKilogram
Run Code Online (Sandbox Code Playgroud)
我的直觉告诉我应该可以在Haskell中实现类似的功能,但是我找不到任何如何做的例子.
编辑:哦,我的话,这是一个巨大的蠕虫!http://research.microsoft.com/en-us/um/people/akenn/units/CEFP09TypesForUnitsOfMeasure.pdf上有一篇研究论文.我猜测实现整个过程不仅仅是几行代码.夏天项目有人吗?:)
Pet*_*all 11
在newtype中包装数字并为其提供Num实例.
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
newtype GBP n = GBP n deriving (Show, Num, Eq, Ord)
newtype USD n = USD n deriving (Show, Num, Eq, Ord)
Run Code Online (Sandbox Code Playgroud)
用法:
ghci> let a1 = GBP 2
ghci> let a2 = GBP 5
ghci> a1 + a2
GBP 7
ghci> let b1 = USD 3
ghci> let b2 = USD 6
ghci> b1 + b2
USD 9
ghci> a1 + b2 -- should be an error for mixing currencies
<interactive>:8:6:
Couldn't match expected type `GBP Integer'
with actual type `USD Integer'
In the second argument of `(+)', namely `b2'
In the expression: a1 + b2
In an equation for `it': it = a1 + b2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1486 次 |
| 最近记录: |