为假人输入家庭 [英] Type families for dummies

查看:79
本文介绍了为假人输入家庭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给出一个超级简单(少数几行)的例子来了解哪些类型的家庭可以用于它们,它们是什么?

2+ 2种类型家庭的例子

解决方案

这是一个例子:

< pre $ { - #Language TypeFamilies,DataKinds,KindSignatures,GADTs,UndecidableInstances# - }

data Nat = Z | S Nat

type family Plus(x :: Nat)(y :: Nat):: Nat where
Plus'Z y = y
Plus('S x)y ='S(加xy)

数据Vec :: Nat - > * - > *其中
无:: Vec'Z a
缺点:: a - > Vec n a - > Vec('s n)a

append :: Vec m a - > Vec n a - > Vec(Plus mn)a
append无ys = ys
append(Cons x xs)ys = Cons x(追加xs ys)
UndecidableInstances 。你不应该害怕这种扩展。






另一种有用的类型族是与类关联的类型。对于一个真正人为的例子,

  class Box b其中
类型Elem b :: *
elem: :b - > Elem b

Box 的一个实例是键入可以取消某些内容。例如,

 实例Box(Identity x)其中
type Elem(Identity x)= x
elem = runIdentity

实例Box Char其中
类型Elem Char =字符串
elem c = [c]

现在 elem(Identity 3)= 3 elem'x'=x



您也可以使用类型族创建奇怪的skolem变量。这最好在尚未发布的GHC 8.0.1中完成,它看起来像

 类型系列任何:: k其中{} 

任何都是奇特的类型。这是无人居住的,它不能(特别)是一个阶级的实例,而且是多元主义的。事实证明这对于某些目的非常有用。这种特殊的类型被广告为 unsafeCoerce ,但是 Data.Constraint.Forall 的安全目标用于更多有趣的目的。

Could someone give a super simple (few line) example to get a basic understanding about what type families can be used for and what are they ?

The 2+2 kind of example of type families ?

解决方案

Here's an example:

{-# Language TypeFamilies, DataKinds, KindSignatures, GADTs, UndecidableInstances #-}

data Nat = Z | S Nat

type family Plus (x :: Nat) (y :: Nat) :: Nat where
  Plus 'Z y = y
  Plus ('S x) y = 'S (Plus x y)

data Vec :: Nat -> * -> * where
  Nil :: Vec 'Z a
  Cons :: a -> Vec n a -> Vec ('S n) a

append :: Vec m a -> Vec n a -> Vec (Plus m n) a
append Nil ys = ys
append (Cons x xs) ys = Cons x (append xs ys)

Note that many/most interesting applications of type families require UndecidableInstances. You should not be scared of this extension.


Another useful sort of type family is one associated with a class. For a really contrived example,

class Box b where
  type Elem b :: *
  elem :: b -> Elem b

An instance of Box is a type that something can be pulled out of. For instance,

instance Box (Identity x) where
  type Elem (Identity x) = x
  elem = runIdentity

instance Box Char where
  type Elem Char = String
  elem c = [c]

Now elem (Identity 3) = 3 and elem 'x' = "x".

You can also use type families to make weird skolem variables. This is best done in the as-yet-unreleased GHC 8.0.1, where it will look like

type family Any :: k where {}

Any is a peculiar type. It's uninhabited, it can't be (specifically) an instance of a class, and it's poly-kinded. This turns out to be really useful for certain purposes. This particular type is advertised as a safe target for unsafeCoerce, but Data.Constraint.Forall uses similar type families for more interesting purposes.

这篇关于为假人输入家庭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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