【发布时间】:2012-06-19 17:37:08
【问题描述】:
我一直在尝试创建一类“Strictable”类型。原因是我想定义这样的东西:
foldl'' f z = foldl' f (make_strict z)
所以当fold'' 用于strictable 类型时,不会有未评估的thunk。
所以我从以下开始:
{-# LANGUAGE TypeFamilies #-}
class Strictable a where
type Strict a :: *
make_strict :: a -> Strict a
为Ints 和Floats 定义实例很容易,foldl' 已经可以很好地处理这些实例,因此无需执行任何操作。
instance Strictable Int where
type Strict Int = Int
make_strict = id
instance Strictable Float where
type Strict Float = Float
make_strict = id
这是棘手的部分。 foldl' 只展开最外层的构造函数,因此以一对为例,您仍然可以使用 foldl' 获得空间泄漏。我想从一个普通的配对中创建一个严格的配对。所以我尝试了这个:
instance (Strictable a, Strictable b) => Strictable (a, b) where
type Strict (a, b) = (! Strict a, ! Strict b)
make_strict (x1, x2) = (make_strict x1, make_strict x2)
不幸的是,我遇到了一堆编译错误。我应该如何实现这个?
【问题讨论】: