本文介绍了Haskell无法与实际类型'Char'匹配预期类型'String'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想知道为什么我得到这个错误。这是一个任务,我要从一个整数转换为十六进制值。当我通过 typeclass: toHexDigit :: Int - > Char 到HexDigit x | x | x | x |否则=错误toHex:数字值太大 更一般地说,任何时候你有一个像: fx | x == A = ... | x == B = ... | x == C = ... ... 您可以将其转换为 case : fx = case x A - > ... B - > ... C - > ... ... I am wondering why I'm getting this error. It's for an assignment where i'm to convert from an integer to a hex value. I call this helper conversion function when I mod the integer value by 16. (concatenated with the integer value which I then divide by 16 in a recursive call)Here is my code: changeToHex :: Integer -> String --main function toHex :: Integer -> String toHex x |x == 0 = '0' |x == 1 = '1' |x == 2 = '2' |x == 3 = '3' |x == 4 = '4' |x == 5 = '5' |x == 6 = '6' |x == 7 = '7' |x == 8 = '8' |x == 9 = '9' |x == 10 = 'A' |x == 11 = 'B' |x == 12 = 'C' |x == 13 = 'D' |x == 14 = 'E' |x == 15 = 'F' 解决方案 Using single quotes ('F') gives you a Char literal. For a String literal, which is in fact a list of Char values, you should use double quotes ("F").Since String is an alias for [Char], if you want to convert from a Char to a String, you can merely wrap the Char in a one-element list. A function to do so might look like:stringFromChar :: Char -> StringstringFromChar x = [x]This is typically written inline, as (:[]), equivalent to \x -> (x : []) or \x -> [x].As an aside, you can simplify your code considerably, using for example the Enum typeclass:toHexDigit :: Int -> ChartoHexDigit x | x < 0 = error "toHex: negative digit value" | x < 10 = toEnum $ fromEnum '0' + x | x < 15 = toEnum $ fromEnum 'A' + x - 10 | otherwise = error "toHex: digit value too large"More generally, any time you have a function like:f x | x == A = ... | x == B = ... | x == C = ... ...You can convert that to a less repetitious, more efficient equivalent with case:f x = case x of A -> ... B -> ... C -> ... ... 这篇关于Haskell无法与实际类型'Char'匹配预期类型'String'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-22 14:02