Haskell:应用多态函数两次

时间:2016-02-21 21:24:03

标签: haskell

我们可以为不同的f :: a -> ba对实现多态函数b。我们怎么做

twice :: (a -> b) -> a -> c
twice f x = f (f x)

键入检查?即如何编写一个两次应用多态函数的函数?

使用Rank2Types,我们可以更接近但不完全在那里:

{-# LANGUAGE Rank2Types #-}

twice1 :: (forall a. a -> (m a)) -> b -> (m (m b))
twice1 f = f . f

twice2 :: (forall a. m a -> a) -> m (m b) -> b
twice2 f = f . f

所以一些多态函数可以应用两次:

\> twice1 (:[]) 1
[[1]]
\> twice2 head [[1]]
1

我们可以走得更远吗?

The question was asked over Haskell cafe 10年前但是没有得到很好的解答(类型类会变成很多样板)。

2 个答案:

答案 0 :(得分:3)

{-# LANGUAGE TypeFamilies, RankNTypes, UnicodeSyntax #-}

type family Fundep a :: *

type instance Fundep Bool = Int
type instance Fundep Int = String
...

twice :: ∀ a . (∀ c . c -> Fundep c) -> a -> Fundep (Fundep a)
twice f = f . f

现在,实际上没有多大用处,因为你无法定义一个与任何 c一起使用的(有意义的)多态函数。一种可能性是抛出类约束,比如

class Showy a where
  type Fundep a :: *
  showish :: a -> Fundep a

instance Showy Bool where
  type Fundep Bool = Int
  showish = fromEnum
instance Showy Int where
  type Fundep Int = String
  showish = show

twice :: ∀ a b . (Showy a, b ~ Fundep a, Showy b) =>
    (∀ c . Showy c => c -> Fundep c) -> a -> Fundep b
twice f = f . f

main = print $ twice showish False

答案 1 :(得分:3)

即使在依赖类型的设置中,您也无法使twice足够通用,但是交叉类型可以实现:

twice :: (a -> b /\ b -> c) -> a -> c
twice f x = f (f x)

现在每当f :: a -> bf :: b -> c类型检查时,twice都会进行类型检查。

Benjamin Pierce's thesis中还有一个漂亮的咒语(我略微改变了语法):

self : (A /\ A -> B) -> B
self f = f f

因此,自我应用程序也可以使用交集类型进行输入。