Int -> Int 是否值得宣布 type Price = Int 使函数变为 priceOfProduc-6ren">
gpt4 book ai didi

haskell - type "name"= Int - 值得声明吗?

转载 作者:行者123 更新时间:2023-12-04 06:31:30 24 4
gpt4 key购买 nike

我有一个返回产品价格的函数,它目前看起来像

priceOfProduct:: Int -> Int -> Int

是否值得宣布
type Price = Int

使函数变为
priceOfProduct :: Int -> Int -> Price ?

我想到了这样做,然后我继续使用 Ints 的元组,如果它们是它们自己的数据结构,它们可能看起来会更好。
priceVsTaxed -> Price -> Int -> (Price, Price)

这有用吗?这是必要的吗?

这是好的 Haskell 风格吗?

声明一个看起来更像是重命名现有数据结构的好样式的数据结构吗?

最佳答案

定义额外的类型并不总是值得的,但绝对要避免Int -> ... -> Int签名。这些使得很难理解应该如何使用函数。

所以事实上我会说你可能不仅应该重命名结果,而且特别是参数。然后,如果有人想使用你的函数,他们可以让编译器解释参数:

foo :: Price
foo = priceOfProduct _ _ + priceOfProduct _ _

将给出一个编译器 (GHC>=7.10) 消息,例如
Foo.hs:Y:X: error:
• Found hole: _ :: PriceOfProductFirstArgument
• In the first argument of ‘priceOfProduct’, namely ‘_’
In the expression: priceOfProduct _ _
In an equation for ‘foo’: main = foo = priceOfProduct _ _ + priceOfProduct _ _

但是,您应该考虑是否不想使类型区分更加严格:简单的 type def 永远无法使您免于将论点置于错误的顺序中,所以也许您最好做到
newtype Price = Price {priceInEuroCents :: Int}

这也避免了价格以何种货币/数量给出的歧义。

关于haskell - type "name"= Int - 值得声明吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47350937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com