[英]Is there a Haskell equivalent of F# units of measure?
F#具有度量單位功能,如http://msdn.microsoft.com/en-us/library/dd233243.aspx所述,如下所示:
[<Measure>] type unit-name [ = measure ]
這允許定義單位,例如:
type [<Measure>] USD
type [<Measure>] EUR
代碼寫成:
let dollars = 25.0<USD>
let euros = 25.0<EUR>
// Results in an error as the units differ
if dollars > euros then printfn "Greater!"
它還處理轉換(我猜這意味着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
我的直覺告訴我應該可以在Haskell中實現類似的功能,但是我找不到任何如何做的例子。
編輯:哦,我的話,這是一個巨大的蠕蟲! http://research.microsoft.com/en-us/um/people/akenn/units/CEFP09TypesForUnitsOfMeasure.pdf上有一篇研究論文。 我猜測實現整個過程不僅僅是幾行代碼。 夏天項目有人嗎? :)
在newtype中包裝數字並為它們提供Num
實例。
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
newtype GBP n = GBP n deriving (Show, Num, Eq, Ord)
newtype USD n = USD n deriving (Show, Num, Eq, Ord)
用法:
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
好。 我知道這個問題太老了。 但是,有一個GHC插件構建來提供Haskell中的度量單位功能。 請參閱這篇Adam Gundry的論文 。
單位包似乎很有希望,並允許在相同維度的不同單位之間進行轉換。 但是,我沒有使用它,我不知道它是否穩定。 公平地說,我今天嘗試安裝它,安裝失敗了......
請先查看haskell.org wikipage,了解有關在Haskell中強制執行單元的信息:
https://wiki.haskell.org/Physical_units
有多種選擇,但我不確定是否確實存在類似於您提到的“計量單位”的內容。
我不太了解Haskell雖然我對學習感興趣並且仍然使用F#,但是,似乎一般的解決方案應該是將度量視為標量元組和表示單位的標簽(N,M)。
例如,讓measure為measure<N,M>
的通用元組,其中N
是數字, M
是string
,則=, +, -, *, /, ^
可以重載以實現對給定度量的評估, a, b, and c
,標量p
,布爾k和測量標簽歸一化函數norm
,使得
a = b = (Na,Ma) = (Nb,Mb) = (Na = Nb) and norm(Ma) = norm(Mb) = k
a + b = (Na,Ma) + (Nb,Mb) = (Na + Nb, Ma) = c provided norm(Ma) = norm(Mb)
a * b = (Na,Ma) * (Nb,Mb) = (Na * Nb, Ma * Mb) = c
a ^ p = (Na,Ma) ^ p = (Na ^ p , Ma ^ p ) = c
....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.