【问题标题】:Purescript: Could not match typePurescript:无法匹配类型
【发布时间】:2018-05-03 08:16:07
【问题描述】:

在 REPL 中这是有效的:

> mm n = (\n -> n * 2) <$> n
> mm (2:3:Nil)
(4 : 6 : Nil)

在这个编译的文件中,我可以运行它:

squareOf ls =
  map (\n -> n * n)  ls

但是当我向该函数添加类型定义时

squareOf :: List Int -> Int
squareOf ls =
  map (\n -> n * n)  ls

我收到一个错误:

 Could not match type

    List Int

  with type

    Int


while checking that type t0 t1
  is at least as general as type Int
while checking that expression (map (\n ->
                                       (...) n
                                    )
                               )
                               ls
  has type Int
in value declaration squareOf

where t0 is an unknown type
      t1 is an unknown type

我尝试将签名更改为列表的类型别名,并且我尝试了一个 forall 定义但没有运气。 如果我检查未在函数中添加签名时创建的定义,我会得到:

forall t2 t3. Functor t2 => Semiring t3 => t2 t3 -> t2 t3

谁能解释为什么我的签名不正确以及为什么我会得到这个函数的签名?

干杯

编辑:感谢 cmets,更新 fn 定义使其也返回 List Int,当然它解决了问题

【问题讨论】:

  • 检查函数的返回类型:Int。但是 map 是结构保留的,所以它必须在你的例子中返回一个 List 的东西。

标签: purescript


【解决方案1】:

假设您的 repl 函数是您所追求的行为,那么您在以后的定义中错过了 map 运算符 (&lt;$&gt;)。

您的 repl 函数(为清楚起见已重命名变量)具有以下类型:

mm :: forall f. Functor f => f Int -> f Int
mm ns = (\n -> n * 2) <$> ns

也就是说:mm 将“乘以 2”映射到可映射的东西”(即 Functor)

除此之外:您可以在此处的定义中更加简洁/清晰:

mm :: forall f. Functor f => f Int -> f Int
mm = map (_*2)

这类似于您的 squareOf 定义,只是现在您是平方,因此您对 (*) 的使用更普遍:

squareOf :: forall f. Functor f => Semiring n => f n -> f n
squareOf = map \n -> n * n

因为(*) 是 Semiring 类型类的成员。

但是你给它的签名表明你在寻找某种fold?让我知道您对 squareOf 函数的期望输出,我会相应地更新答案。

【讨论】:

    【解决方案2】:

    这里是map:

    class Functor f where
      map :: forall a b. (a -> b) -> f a -> f b
    

    缩小到List Int和Int -&gt; Int,编译器推断

    map :: (Int -> Int) -> List Int -> List Int
    

    因此,在squareOf 中,表达式简化为整数列表,而不是整数。这就是编译器抱怨的原因。

    【讨论】:

      猜你喜欢
      • 2015-07-13
      • 2014-12-11
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      相关资源
      最近更新 更多