无法将预期类型“字符-> [字符]-> t”与实际类型“字符”匹配

时间:2019-03-20 05:13:21

标签: haskell

我写了一个函数,用给定元素替换列表中的某些元素。

subst :: Eq t => t -> t -> [t] -> [t]
subst a b [] = []
subst a b (x:xs) = if a == x
                   then b : subst a b xs
                   else
                   subst a b xs

当我用0 1 [0,1,2,3]测试它时,这就是它的显示内容

*Main> 0 1 [0,1,2,3]

<interactive>:68:1: error:
    • Non type-variable argument
        in the constraint: Num (t1 -> [a] -> t2)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall t1 a t2. (Num t1, Num a, Num (t1 -> [a] -> t2)) => t2

当我使用'e''a'“ hello”测试它时,反馈如下所示:

*Main> 'e' 'a' "hello"

<interactive>:69:1: error:
    • Couldn't match expected type ‘Char -> [Char] -> t’
                  with actual type ‘Char’

    • The function ‘'e'’ is applied to two arguments,
      but its type ‘Char’ has none
      In the expression: 'e' 'a' "hello"
      In an equation for ‘it’: it = 'e' 'a' "hello"
    • Relevant bindings include it :: t (bound at <interactive>:69:1)

某人可以帮助我解释正在发生的事情以及为什么它不起作用吗?

1 个答案:

答案 0 :(得分:3)

您没有正确使用GHCi。您必须将main.hs函数应用于一些参数才能对其求值。

假设您的代码位于名为GHCi, version 8.4.3: http://www.haskell.org/ghc/ :? for help Loaded GHCi configuration from /Users/jgt/.ghci λ :l main [1 of 1] Compiling Main ( main.hs, interpreted ) Ok, one module loaded. λ subst 0 1 [0,1,2,3] [1] 的文件中,这就是它的工作方式:

λ

n.b。您可以忽略我的提示是:set prompt "λ "的事实;您可以使用{{1}}设置自己的提示。