【问题标题】:Haskell rank n types & type classes syntaxHaskell rank n 类型和类型类语法
【发布时间】:2016-09-27 07:52:11
【问题描述】:

在学习 Haskell 时,我试图了解 Haskell 中 clojure 转换器的类型。

{-# LANGUAGE RankNTypes #-}

module Transducers where

-- r = reduced
type Reducer r a = r -> a -> r

type Transducer a b = forall r . Reducer r a -> Reducer r b

我无法理解如何键入以下函数:

-- type inference
transduce :: Foldable t => (t1 -> b -> a -> b) -> t1 -> b -> t a -> b
-- what I actually want
transduce :: forall t1 . Foldable t => Transducer a b -> t1 -> b -> t a -> b
transduce xform f init coll = foldl (xform f) init coll

这给我带来了麻烦,它不会编译。我是否缺少语法方面的东西?或者这不可能吗?

【问题讨论】:

  • 你能举一个更完整的例子来说明你正在尝试做什么吗?为什么不只拥有transduce :: Foldable t => Transducer a b -> Reducer r a -> r -> t b -> r
  • 显然Foldable t => Transducer a b -> t1 -> b -> t a -> b 类型对于给定的实现是错误的。 xform 的类型为 Transducer a b,它是一个函数,对某些 r0 采用 Reducer r0 a,但您将 xform 应用于 f,其类型为 t1(刚性类型!),这显然不是没道理。推断类型 Foldable t => (t1 -> b -> a -> b) -> t1 -> b -> t a -> b 可能是您真正想要的 - 第一个参数不是转换器,但您可以传递一些是转换器的东西。如果您想推理来猜测多型,请将Transducer 包装在一个新类型中。

标签: haskell polymorphism


【解决方案1】:

在我看来你的意思可能是这样的

transduce :: Foldable t => Transducer a b -> Reducer r a -> r -> t b -> r

作为user2407038 suggested,如果你想强制调用者提供Transducer,你只需要这样一个花哨的类型。否则,您可以将其简化为

transduce :: Foldable t => (x -> Reducer r b) -> x -> r -> t b -> r

【讨论】:

  • 谢谢,我现在明白了:)
猜你喜欢
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多