我希望将两个字符之间的加法定义为隐含性,但不确定如何正确执行。
我的尝试:
instance Num Char where
(+) (a) (b) = [a] ++ [b]
Run Code Online (Sandbox Code Playgroud)
但是我得到的错误是返回类型不是预期的类型。
如前所述,我的预期输出是将两个字符叠加而成的字符列表。
Rather than overload (+) with non-numeric semantics, define your own character "addition" operator.
import Data.Function
-- The ^ is meant to suggest lifting values into a list.
(^+) :: a -> a -> [a]
x ^+ y = (++) `on` pure
-- Or more simply,
-- x ^+ y = [x, y]
Run Code Online (Sandbox Code Playgroud)
Then 'a' ^+ 'b' == "ab". (^+) will work for creating a two-element list of any type, not just Char.
> 'a' ^+ 'b'
"ab"
> 3 ^+ 4
[3,4]
> [1,2] ^+ [4,5]
[[1,2],[4,5]]
Run Code Online (Sandbox Code Playgroud)
这是不可能的。中的(+)函数Num具有type a -> a -> a,因此返回类型必须与参数类型相同。您不能添加两个Char并因此收到String。更一般而言,除了对数字进行算术运算外,您不应该为其他事情实现Num。