简体   繁体   English

Haskell在哪里进行类型声明

[英]Haskell where type declaration

I'm new to Haskell and having trouble with the type system. 我是Haskell的新手,并且在类型系统方面遇到了麻烦。 I have the following function: 我有以下功能:

threshold price qty categorySize
    | total < categorySize = "Total: " ++ total ++ " is low"
    | total < categorySize*2 = "Total: " ++ total ++ " is medium"
    | otherwise = "Total: " ++ total ++ " is high"
    where total =  price * qty

Haskell responds with: Haskell回应:

No instance for (Num [Char])
      arising from a use of `*'
    Possible fix: add an instance declaration for (Num [Char])
    In the expression: price * qty
    In an equation for `total': total = price * qty
    In an equation for `threshold':
     ... repeats function definition

I think the issue is that I need to somehow tell Haskell the type of total, and maybe associate it with the type class Show, but I don't know how to accomplish that. 我认为问题是我需要以某种方式告诉Haskell总类型,并且可能将它与类型Show相关联,但我不知道如何实现它。 Thanks for any help. 谢谢你的帮助。

The problem is you define total as the result of a multiplication, which forces it to be a Num a => a and then you use it as an argument to ++ with strings, forcing it to be [Char] . 问题是你将total定义为乘法的结果,它强制它为Num a => a然后你用它作为带有字符串的++的参数,强制它为[Char]

You need to convert total to a String : 您需要将total转换为String

threshold price qty categorySize
    | total < categorySize   = "Total: " ++ totalStr ++ " is low"
    | total < categorySize*2 = "Total: " ++ totalStr ++ " is medium"
    | otherwise              = "Total: " ++ totalStr ++ " is high"
    where total    = price * qty
          totalStr = show total

Now, that will run, but the code looks a little repetitive. 现在,这将运行,但代码看起来有点重复。 I would suggest something like this: 我会建议这样的事情:

threshold price qty categorySize = "Total: " ++ show total ++ " is " ++ desc
    where total = price * qty
          desc | total < categorySize   = "low"
               | total < categorySize*2 = "medium"
               | otherwise              = "high"

The problem appears to be that you need to explicitly convert between strings and numbers. 问题似乎是您需要在字符串和数字之间进行显式转换。 Haskell will not automatically coerce strings to numbers or vice versa. Haskell不会自动将字符串强制转换为数字,反之亦然。

To convert a number for display as a string, use show . 要将数字转换为字符串显示,请使用show

To parse a string into a number, use read . 要将字符串解析为数字,请使用read Since read actually applies to many types, you may need to specify the type of the result, as in: 由于read实际上适用于许多类型,因此您可能需要指定结果的类型,如:

price :: Integer
price = read price_input_string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM