是否有一个Haskell等价的F#度量单位?

Dar*_*ren 15 f# haskell

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)

  • 我不太了解Haskell,但F#单元的一个强大功能是它们支持乘法 - 例如`1 <m>/1 <s> = 1 <m/s>`这意味着你可以获得类型检查的支持物理方程组.你的Haskell实现了吗? (9认同)
  • @JohnPalmer你的例子当然可以防止对一种类型的意外处理,因为另一种类型与Java和C#一样强大!我很想知道是否有可能在Haskell中实现F#示例的全部功能(或者确实是为了找出他们是否以某种方式作弊并将其融入语言中). (2认同)
  • 导出的问题是"Num",它允许乘法错误(因为乘法单位应该改变维度) (2认同)

Dou*_*ean 7

二维-TF(有型的家庭,而不是多参数类型类)库是相当不错的,并能处理大部分的在你的例子提出了这些问题.

我认为库不允许您定义像货币这样的自定义维度.据我所知,你需要修改库代码才能做到这一点.