ERROR: no instance for (Num Char) arising from the literal `1'

ERROR: no instance for (Num Char) arising from the literal `1'

insert_at 将元素 e 插入列表 xs 的特定位置 n

test如果 n 小于 0

则得到 Left

test2 如果 n 大于 xs 的长度或 类型 e 与列表中元素的类型xs。否则将 Right xs 传递给下一个

import Data.Typeable

insert_at :: a -> [a] -> Int -> [a]
insert_at e xs n = a++(e:b) where
    t = splitAt n xs
    a = fst t
    b = snd t 
test :: (Ord a, Num a) => b -> a -> Either [Char] b
test xs n = if n < 0 then Left "n<0" else Right xs

test2 :: (Typeable a1, Typeable a2) =>
           a1 -> [a2] -> Int -> Either [Char] [a2]
test2 e xs n 
        | n> ( length xs )= Left "n> $ length xs "
        | (typeOf e) /= (typeOf (head xs) ) = Left "(typeOf e) /= (typeOf (head xs) ) "
        |otherwise = Right xs

sf :: Typeable a => a -> [a] -> Int -> Either [Char] [a]
sf e xs n = test xs n >>test2 e xs n >> Right (insert_at e xs n)

所有其他错误都已得到妥善处理,希望如此。

* No instance for (Num Char) arising from the literal `1'
    * In the expression: 1
      In the second argument of `sf', namely `[1, 2, 3, 4, ....]'
      In the expression: sf 'a' [1, 2, 3, 4, ....] 3

sf 需要一个值和一个列表作为它的前两个参数。列表的元素必须与第一个参数具有相同的类型。这是

的意思
sf :: a -> [a] -> ...

当你写 sf 'a' [1] 时,这意味着 1'a' 必须具有相同的类型。所以类型检查器寻找一种方法将 1 解释为 Char;它失败了,因为这是不可能的。一些修复可能包括:

sf 'a' "1234" 3
sf 'a' [toEnum 1, toEnum 2, toEnum 3, toEnum 4] 3
sf (fromEnum 'a') [1, 2, 3, 4] 3

错误消息表明您正在尝试计算表达式 sf 'a' [1, 2, 3, 4, ....] 3。由于此表达式未显示在您的问题中,我假设您在 GHCi 中使用它来测试您的代码,对吗?

sf的类型签名说第一个参数的类型是a,第二个参数的类型是[a],是一个元素类型相同的列表作为第一个参数。

所以编译器看到第一个参数是'a'。那是一个字符,输入 Char.

“明白了,”- 编译器认为,-“现在我知道 aChar。现在我知道第二个参数的类型必须是 [Char] -即 Char".

的列表

是的,第二个参数确实是一个列表,但是等等!列表的第一个元素不是字符,而是数字1!那不计算!

幸运的是,数字文字在 Haskell 中很特殊。数字文字不仅是 Int 类型甚至 Integer 类型,不!数字可以是 任何 类型,只要该类型具有 class Num.

的实例

因此,由于编译器已经知道该列表的元素必须是 Char 类型,但它看到一个数字文字,因此得出结论,它现在必须找到 class Num 类型 Char.

但是没有这样的例子!因此编译器正确地抱怨:“没有实例Num Char


要解决此问题,我需要更好地了解您实际尝试做的事情。

您是否打算让整个函数都处理数字?那么第一个参数必须是数字,不能是字符。

或者您打算将其用于角色?那么第二个参数必须是字符列表,不能是数字。

或者您是否打算让前两个参数完全不是同一类型?那么您必须更改 sf 的类型签名以表明这一点。