简体   繁体   English

为什么不使用“==”添加“Eq”类型约束?

[英]Why add “Eq” type constraint without using “==”?

So, I have a very simple function that take two parameters : the first is a hour (between 0 and 23) and the second one is a minute (between 0 and 59). 所以,我有一个非常简单的函数,它有两个参数:第一个是小时(0到23之间),第二个是一分钟(0到59之间)。 This function return the hour plus one minute, and format the hour in a beautiful style. 此功能返回小时加一分钟,并以美丽的风格格式化小时。 By example, hour 11 12 return 11 heures et 13 minutes . 例如, hour 11 12返回11 heures et 13 minutes Sorry for the french format of the hour. 对不起,小时的法语格式。

So, I use in this function the show function, and the parameters need to be a number, so I have the type declaration (Num a, Show a) => a -> a -> String . 所以,我在这个函数中使用show函数,并且参数需要是一个数字,所以我有类型声明(Num a, Show a) => a -> a -> String But, when I try the function, I got an error and GHC say to me to add the Eq type constraint, but I don't understand why I need the Eq type constraint in this case. 但是,当我尝试该函数时,我收到一个错误,GHC告诉我添加Eq类型约束,但我不明白为什么在这种情况下我需要Eq类型约束。 There is the code (again, sorry for the french text used in the function, but I think that it's not very important if you don't understand the function name and the text) : 有代码(再次,对于函数中使用的法语文本感到遗憾,但我认为如果你不理解函数名和文本,这不是很重要):

heure :: (Num a, Eq a, Show a) => a -> a -> String
heure 23 59 = "Minuit"
heure 12 m  = "Midi et " ++ show (m+1) ++ " minutes"
heure h 59  = show (h+1) ++ " heures"
heure h m   = show h ++ " heures et " ++ show (m+1) ++ " minutes"

So : if I don't use Eq , I have an error and when I use it my code is correct. 所以:如果我不使用Eq ,我有一个错误,当我使用它时,我的代码是正确的。 Why? 为什么?

Thank you for your explanations! 谢谢你的解释!

You need the Eq constraint because you're checking whether h is equal to 23 or 12 and whether m is equal to 59 . 您需要Eq约束,因为您正在检查h是否等于2312以及m是否等于59 You're doing it using pattern matching, not == , but pattern matching against numeric literals that way still requires Eq (unlike pattern matching against constructors). 你正在使用模式匹配,而不是== ,但是对数字文字的模式匹配仍然需要Eq (与构造函数的模式匹配不同)。

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

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