Haskell安全货币示例

4

这位杰出的作者通过他们优秀的博客文章彻底地使我相信使用safe-money:

https://ren.zone/articles/safe-money

但是当我在 GHCi 中尝试示例并尝试各种 import 语句时,即使重新输入博客文章中的确切样例,我也无法让它正常工作:

Prelude> :m Data.Ratio

Prelude Data.Ratio> 1 % 5
1 % 5

...

Prelude Data.Ratio Data.Text> :m +Money

Prelude Data.Ratio Data.Text Money> :t dense
dense :: Rational -> Maybe (Dense currency)

Prelude Data.Ratio Data.Text Money> let y = 5 :: Integer
Prelude Data.Ratio Data.Text Money> :t y
y :: Integer
Prelude Data.Ratio Data.Text Money> y % 100
1 % 20
Prelude Data.Ratio Data.Text Money> :t it
it :: Ratio Integer
Prelude Data.Ratio Data.Text Money> let z = y % 100
Prelude Data.Ratio Data.Text Money> :t z
z :: Ratio Integer
Prelude Data.Ratio Data.Text Money> dense z

<interactive>:30:1: error:
    • No instance for (GHC.TypeLits.KnownSymbol currency0)
        arising from a use of ‘print’
    • In a stmt of an interactive GHCi command: print it

Prelude Data.Ratio Data.Text Money> fromRational z
5.0e-2
Prelude Data.Ratio Data.Text Money> :t it
it :: Fractional a => a

Prelude Data.Ratio Data.Text Money> fromRational z :: Dense "USD"

<interactive>:35:25: error:
    Illegal type: ‘"USD"’ Perhaps you intended to use DataKinds
Prelude Data.Ratio Data.Text Money> 'fromRational' z :: Dense "USD"

<interactive>:36:1: error:
    • Syntax error on 'fromRational'
      Perhaps you intended to use TemplateHaskell or TemplateHaskellQuotes
    • In the Template Haskell quotation 'fromRational'

<interactive>:36:27: error:
    Illegal type: ‘"USD"’ Perhaps you intended to use DataKinds
Prelude Data.Ratio Data.Text Money>  'fromRational' (341 % 100) :: Dense "USD"

<interactive>:37:2: error:
    • Syntax error on 'fromRational'
      Perhaps you intended to use TemplateHaskell or TemplateHaskellQuotes
    • In the Template Haskell quotation 'fromRational'

<interactive>:37:38: error:
    Illegal type: ‘"USD"’ Perhaps you intended to use DataKinds


我希望像这样聪明的作者也能实用一些,为初学到中级的Haskeller提供步骤零的基础知识。
在*ackage页面和Github上也没有很多内容。有人能够提供一个使用“safe-money”的可行示例吗?我肯定被Yesod文档中的完整示例惯坏了。
我相信这个包就是:https://hackage.haskell.org/package/safe-money

5
在会话开始时尝试使用 :set -XDataKinds - luqui
5
我不知道'fromRational' (341%100)中引号的用法是什么。在我所知道的任何Haskell环境中都是无效的。 备注:该句子已经是中文,需要翻译的内容为英文。 - luqui
1个回答

2

正如luqui所评论的那样,您需要启用DataKinds扩展。

您可以在文件中启用此扩展:

{-# LANGUAGE DataKinds #-}

您可以在GHCi中启用此功能,方法如下:

:set -XDataKinds

在GHCi中提供的错误信息应该是启用该扩展的好提示。

非法类型:“USD”,也许您想使用DataKinds。

通过浏览此处的搜索结果,您可以查看更多的用法示例:https://github.com/search?q=import+Money+dense+language%3Ahaskell&type=Code

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接