依赖类型的教堂编码:从Coq到Haskell [英] Church encoding for dependent types: from Coq to Haskell

查看:154
本文介绍了依赖类型的教堂编码:从Coq到Haskell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Coq中,我可以为长度为n的列表定义教堂编码:

In Coq I can define a Church encoding for lists of length n:

Definition listn (A : Type) : nat -> Type :=
fun m => forall (X : nat -> Type), X 0 -> (forall m, A -> X m -> X (S m)) -> X m.

Definition niln (A : Type) : listn A 0 :=
fun X n c => n.

Definition consn (A : Type) (m : nat) (a : A) (l : listn A m) : listn A (S m) :=
fun X n c => c m a (l X n c).

Haskell的类型系统(包括其扩展名)是否足够强以容纳此类定义?如果是,怎么办?

Is the type system of Haskell (including its extensions) strong enough to accommodate such definitions? If yes, how?

推荐答案

确定是

{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}

import Data.Kind        -- Needed for `Type`

data Nat = Z | S Nat    -- Roll your own...

type List (a :: Type) (n :: Nat) =
  forall (x :: Nat -> Type). x Z -> (forall (m :: Nat). a -> x m -> x (S m)) -> x n

niln :: List a Z
niln = \z _ -> z

consn :: a -> List a n -> List a (S n)
consn a l = \n c -> c a (l n c)

使用常规GADT公式进一步证明(对于怀疑论者)同构:

Further proof (for skeptics) of the isomorphism with the usual GADT formulation:

data List' (a :: Type) (n :: Nat) where
  Nil :: List' a Z
  Cons :: a -> List' a m -> List' a (S m)

to :: List' a n -> List a n
to Nil = niln
to (Cons a l) = consn a (to l)

from :: List a n -> List' a n
from l = l Nil Cons

这篇关于依赖类型的教堂编码:从Coq到Haskell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆