【发布时间】: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