【问题标题】:Couldn't match expected type ‘[Char]’ with actual type ‘Int’无法将预期类型“[Char]”与实际类型“Int”匹配
【发布时间】:2019-04-23 06:35:02
【问题描述】:

正在研究一种将数字 n 转换为任何基数 b 的方法,但遇到了一些麻烦。

代码:

int2Base :: Int -> Int -> String
int2Base n b
    |n == 0 = "0"
    |otherwise = (mod n b) ++ int2Base (div n b) b

我的错误:

Couldn't match expected type ‘[Char]’ with actual type ‘Int’
In the second argument of ‘mod’, namely ‘b’
In the first argument of ‘(++)’, namely ‘(mod n b)’

这似乎是一个简单的错误,但即使我将其转换为 char,它仍然期望 '[Char]' 而不是 [Char]

【问题讨论】:

  • 确实不能将 Int 连接到字符串。您需要将其转换为 Char,然后将其添加到前面(使用 (:))。一旦你这样做了,你会发现你正在反向构建你的结果!
  • 我应该如何将它转换为char?我试过 fromEnum 但这似乎不起作用
  • 当你说“任何基础”时,你真的是指b <= 10吗?

标签: haskell


【解决方案1】:

问题出在这里:

(mod n b) ++ int2Base (div n b) b

"(mod n b)" 生成一个 Int,而不是 String。

这应该可以解决它:

int2Base :: Int -> Int -> String
int2Base n b
    |n == 0 = "0"
    |otherwise = show(mod n b) ++ int2Base (div n b) b

【讨论】:

  • 不过,这将为 b > 10 产生愚蠢的结果。
【解决方案2】:

如果你在 GHCI 中查看 ++

Prelude> :t (++)
(++) :: [a] -> [a] -> [a]

所以 ++ 只能应用于列表,而 [char] 是一个字符列表。

如果您想将此 Int 值转换为 String/[Char],您可以使用 show

Prelude> :t show
show :: Show a => a -> String

这意味着节目能够采用“a”表示的某些类型并返回字符串。

所以要修复错误,您可以使用otherwise = show(mod n b) ++ int2Base (div n b) b

这将确保您将函数类型与字符串列表匹配

int2Base :: Int -> Int -> String
int2Base n b
  |n == 0 = ['0']
  |otherwise = show(mod n b) ++ int2Base (div n b) b

(我使用 ['0'] 只是为了说明双引号中的字符串如何保持 [chars] 类型

【讨论】:

    猜你喜欢
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    相关资源
    最近更新 更多