SlideShare a Scribd company logo
Зависимые типы в GHC 8
Максим Талдыкин
max@formalmethods.ru
Зависимые типы в GHC 8. Максим Талдыкин
Что такое?
Just 1 : Maybe Int : * : □
Maybe : * -> * : □
Vec Int Z : * : □
Vec : * -> Nat -> * : □
map : forall a b. (a -> b) -> [a] -> [b]
map f (x:xs) = f x : map f xs
map f [] = []
map :: forall a b. (a -> b) -> [a] -> [b]
map =
 (@a)
(@b)
(f :: a -> b)
(ds :: [a]) ->
case ds of
[] -> GHC.Types.[] @b
: x xs ->
GHC.Types.: @b (f x) (map @a @b f xs)
forall
(a :: *)
(b :: *)
(f :: a -> b)
(xs :: [a])
. [b]
replicate :: pi (n : Nat) -> a -> Vec a n
replicate Z _ = Nil
replicate (S m) x = x :> replicate m a
vis dep rel
forall (a : *). a - + -
a -> a + - +
Monad m => m a - - +
pi (a : Bool). f a - + +
pi (a : Bool) -> f a + + +
* : *
pi
Зачем?
zipWithN, mapT
tail []
strncpy
:: forall (p q :: Nat)
=> (LE n p ~ True, LE n q ~ True)
. pi (n :: Nat)
-> Ptr Char p
-> Ptr Char q
-> IO ()
Π-Ware: Hardware Description
Swierstra et al., 2015
Correct-by-Construction Concurrency
Brady & Hammond, 2009
Security-Typed Programming
Morgenstern & Licata, 2010
Type Families
data Nat = Z | S Nat
type family
(m :: Nat) :+ (n :: Nat) :: Nat
where
Z :+ n = n
(S k) :+ n = S (k :+ n)
-- Vec a m -> Vec a n -> Vec a (m :+ n)
GADTs
Generalized Algebraic Data Types
data Vec :: Nat -> * -> *
Nil :: Vec Z a
(:>) :: a -> Vec n a -> Vec (S n) a
data Vec (n :: Nat) (a :: *) :: * where
Nil :: n ~ Z => Nil n a
(:>) :: forall (m :: Nat)
. n ~ S m
=> a -> Vec m a -> Vec n a
tail :: Vec (S k) a -> Vec k a
tail (_ :> xs) = xs
-- (m :: Nat) (S k ~ S m)
type family
(v :: Vec a m) :++ (w :: Vec a n) :: Vec a k
where
Nil :++ w = w
(x :> xs) :++ w = x :> (xs :++ w)
type family
(v :: Vec a m) :++ (w :: Vec a n) :: Vec a k
where
Nil :++ w = w
(x :> xs) :++ w = x :> (xs :++ w)
‘Vec’ of kind ‘* -> Nat -> *’ is not promotable
In the kind ‘Vec a m’
Vec :: □ -> □ -> □
replicate :: pi (n :: Nat) -> a -> Vec a n
replicate Z a = Nil
replicate (S m) a = a :> replicate m a
data Nat = Z | S Nat
data Nat's :: Nat -> * where
Z's :: Nat's Z
S's :: Nat's n -> Nat's (S n)
-- S's Z's :: Nat's (S Z)
replicate :: Nat's n -> a -> Vec a n
replicate Z's a = Nil
replicate (S's m) a = a :> replicate m a
Они уже здесь!
Singleton types here
Singleton types there
Singleton types everywhere
Monnier & Haguenauer, 2009
Hasochism
Lindley & mcBride, 2013
data Fin :: Nat -> * where
FZ :: Fin (S n)
FS :: Fin n -> Fin (S n)
lookup :: pi (f :: Fin n) -> Vec a n -> a
lookup FZ (x :> _) = x
lookup (FS i) (_ :> xs) = lookup i xs
data Fin's (n :: Nat) (f :: Fin n) :: * where
FZ's :: Fin's (S m) FZ
FS's :: Fin's m g -> Fin's (S m) (FS g)
-- FS's FZ's :: Fin's 4 (FS FZ :: Fin 4)
data Fin's (n :: Nat) (f :: Fin n) :: * where
FZ's :: Fin's (S m) FZ
FS's :: Fin's m g -> Fin's (S m) (FS g)
Kind variable also used as type variable: ‘n’
In the data type declaration for ‘Fin's’
get "/Contract/:id" $ do
intParam "id" >>= queryDb "Contract" >>= json
type API
= "Contract"
:> Capture "id" Int
:> Get '[JSON] Contract
type Api
= "Contract"
:> Capture "id" Int
:> RoleFilter "Contract" "owner" '[43, 265]
:> Get '[JSON] (Obj Contract)
data User (fieldName :: Symbol) where
Id :: Int -> User "id"
Name :: Text -> User "name"
Roles :: [Vector (Ref Role)] -> User "roles"
data Contract (fieldName :: Symbol) where
Id :: Int -> Contract "id"
Owner :: Ref Role -> Contract "owner"
type family TableName (m :: Symbol -> *) :: Symbol
type instance TableName User = "User"
type instance TableName Contract = "Contract"
type Api
= "Contract"
:> Capture "id" Int
:> RoleFilter "Contract" "owner" '[43, 265]
:> Get '[JSON] (Obj Contract)
type Api
= MkFilter Contract
(RoleFilter C.Owner '[Role1, Role2])
type family MkFilter
(f :: Symbol)
(m :: Symbol -> *)
(filter :: *)
where
MkFilter f m (RoleFilter (own :: m g) rs)
= TableName m
:> Capture
(FieldName (TableId m))
(FieldType (TableId m))
:> RoleFilter' (TableName m) g rs
:> Get '[JSON] (Obj m)
Termination
Equality
Consistency
System FC with Explicit Kind Equality, 2013
Dependent Types in Haskell, draft
Type Inference, Haskell and Dependent Types, 2013
Stephanie Weirich
Richard A. Eisenberg
Per Martin-Löf, Intuitionistic type theory (1984)
F O R M L   M T H O D S
A
E
Зависимые типы в GHC 8. Максим Талдыкин

More Related Content

DOCX
Code
Fran Orton
 
PPTX
Ricky Bobby's World
Brian Lonsdorf
 
PPTX
Fact, Fiction, and FP
Brian Lonsdorf
 
PPTX
Lenses
Brian Lonsdorf
 
PDF
Metaprogramming
Dmitri Nesteruk
 
PDF
Metarhia KievJS 22-Feb-2018
Timur Shemsedinov
 
PPTX
Super Advanced Python –act1
Ke Wei Louis
 
Ricky Bobby's World
Brian Lonsdorf
 
Fact, Fiction, and FP
Brian Lonsdorf
 
Metaprogramming
Dmitri Nesteruk
 
Metarhia KievJS 22-Feb-2018
Timur Shemsedinov
 
Super Advanced Python –act1
Ke Wei Louis
 

What's hot (19)

PDF
Programming Language: Ruby
Hesham Shabana
 
PDF
JavaScript - Agora nervoso
Luis Vendrame
 
DOCX
Plot3D Package and Example in R.-Data visualizat,on
Dr. Volkan OBAN
 
TXT
Litebox
meli media
 
PDF
Having fun with graphs, a short introduction to D3.js
Michael Hackstein
 
PDF
JavaScript ES6
Leo Hernandez
 
PDF
MongoDB Oplog入門
Takahiro Inoue
 
PDF
Short intro to the Rust language
Gines Espada
 
PDF
Swift - Krzysztof Skarupa
Sunscrapers
 
PPTX
Lab 13
Adnan Raza
 
PPT
C++totural file
halaisumit
 
PPT
C++ tutorial
sikkim manipal university
 
PDF
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
PDF
#RuPostgresLive 4: как писать и читать сложные SQL-запросы
Nikolay Samokhvalov
 
RTF
Class & sub class
HSS-Software House
 
PDF
刘平川:【用户行为分析】Marmot实践
taobao.com
 
PDF
ECMAScript 6 major changes
hayato
 
KEY
cocos2d 事例編 HungryMasterの実装から
Yuichi Higuchi
 
PPT
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
Programming Language: Ruby
Hesham Shabana
 
JavaScript - Agora nervoso
Luis Vendrame
 
Plot3D Package and Example in R.-Data visualizat,on
Dr. Volkan OBAN
 
Litebox
meli media
 
Having fun with graphs, a short introduction to D3.js
Michael Hackstein
 
JavaScript ES6
Leo Hernandez
 
MongoDB Oplog入門
Takahiro Inoue
 
Short intro to the Rust language
Gines Espada
 
Swift - Krzysztof Skarupa
Sunscrapers
 
Lab 13
Adnan Raza
 
C++totural file
halaisumit
 
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
#RuPostgresLive 4: как писать и читать сложные SQL-запросы
Nikolay Samokhvalov
 
Class & sub class
HSS-Software House
 
刘平川:【用户行为分析】Marmot实践
taobao.com
 
ECMAScript 6 major changes
hayato
 
cocos2d 事例編 HungryMasterの実装から
Yuichi Higuchi
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
Ad

Viewers also liked (9)

PDF
Краткий экскурс в системы типов или как избежать дезинтеграции. Денис Редозубов
Юрий Сыровецкий
 
PDF
Евгений Котельников. Зависимые типы в Haskell
FProg
 
PDF
Возможности и проблемы FFI в Haskell. Александр Вершилов
Юрий Сыровецкий
 
PDF
Fast as C: How to Write Really Terrible Java
Charles Nutter
 
PDF
Монады для барабанщиков. Антон Холомьёв
Юрий Сыровецкий
 
PDF
Cloud Haskell. Александр Вершилов
Юрий Сыровецкий
 
PDF
Ленивые вычисления: плюсы и минусы. Денис Шевченко
Юрий Сыровецкий
 
PDF
SREcon 2016 Performance Checklists for SREs
Brendan Gregg
 
PDF
Анонимные записи в Haskell. Никита Волков
Юрий Сыровецкий
 
Краткий экскурс в системы типов или как избежать дезинтеграции. Денис Редозубов
Юрий Сыровецкий
 
Евгений Котельников. Зависимые типы в Haskell
FProg
 
Возможности и проблемы FFI в Haskell. Александр Вершилов
Юрий Сыровецкий
 
Fast as C: How to Write Really Terrible Java
Charles Nutter
 
Монады для барабанщиков. Антон Холомьёв
Юрий Сыровецкий
 
Cloud Haskell. Александр Вершилов
Юрий Сыровецкий
 
Ленивые вычисления: плюсы и минусы. Денис Шевченко
Юрий Сыровецкий
 
SREcon 2016 Performance Checklists for SREs
Brendan Gregg
 
Анонимные записи в Haskell. Никита Волков
Юрий Сыровецкий
 
Ad

Similar to Зависимые типы в GHC 8. Максим Талдыкин (20)

PPTX
Oh Composable World!
Brian Lonsdorf
 
PDF
SATySFiのこれからの課題たち
T. Suwa
 
PDF
Артём Акуляков - F# for Data Analysis
SpbDotNet Community
 
PDF
Intro To Agda
Larry Diehl
 
DOCX
Some Examples in R- [Data Visualization--R graphics]
Dr. Volkan OBAN
 
PDF
The Essence of the Iterator Pattern (pdf)
Eric Torreborre
 
PPTX
Introduction to Monads in Scala (2)
stasimus
 
PDF
Sigma type
Dmytro Mitin
 
PDF
13 - Scala. Dependent pair type (Σ-type)
Roman Brovko
 
PDF
16 - Scala. Type of length-indexed vectors
Roman Brovko
 
PPTX
The Essence of the Iterator Pattern
Eric Torreborre
 
PDF
10. R getting spatial
ExternalEvents
 
PDF
JSDC 2014 - functional java script, why or why not
ChengHui Weng
 
PDF
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 
PDF
Munihac 2018 - Beautiful Template Haskell
Matthew Pickering
 
PDF
Class Customization and Better Code
Stronnics
 
PDF
Stefan Kanev: Clojure, ClojureScript and Why They're Awesome at I T.A.K.E. Un...
Mozaic Works
 
PDF
Declarative Type System Specification with Statix
Eelco Visser
 
PDF
Implementing virtual machines in go & c 2018 redux
Eleanor McHugh
 
PDF
R getting spatial
FAO
 
Oh Composable World!
Brian Lonsdorf
 
SATySFiのこれからの課題たち
T. Suwa
 
Артём Акуляков - F# for Data Analysis
SpbDotNet Community
 
Intro To Agda
Larry Diehl
 
Some Examples in R- [Data Visualization--R graphics]
Dr. Volkan OBAN
 
The Essence of the Iterator Pattern (pdf)
Eric Torreborre
 
Introduction to Monads in Scala (2)
stasimus
 
Sigma type
Dmytro Mitin
 
13 - Scala. Dependent pair type (Σ-type)
Roman Brovko
 
16 - Scala. Type of length-indexed vectors
Roman Brovko
 
The Essence of the Iterator Pattern
Eric Torreborre
 
10. R getting spatial
ExternalEvents
 
JSDC 2014 - functional java script, why or why not
ChengHui Weng
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 
Munihac 2018 - Beautiful Template Haskell
Matthew Pickering
 
Class Customization and Better Code
Stronnics
 
Stefan Kanev: Clojure, ClojureScript and Why They're Awesome at I T.A.K.E. Un...
Mozaic Works
 
Declarative Type System Specification with Statix
Eelco Visser
 
Implementing virtual machines in go & c 2018 redux
Eleanor McHugh
 
R getting spatial
FAO
 

Recently uploaded (20)

PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Software Development Methodologies in 2025
KodekX
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 

Зависимые типы в GHC 8. Максим Талдыкин

  • 1. Зависимые типы в GHC 8 Максим Талдыкин [email protected]
  • 4. Just 1 : Maybe Int : * : □ Maybe : * -> * : □ Vec Int Z : * : □ Vec : * -> Nat -> * : □
  • 5. map : forall a b. (a -> b) -> [a] -> [b] map f (x:xs) = f x : map f xs map f [] = []
  • 6. map :: forall a b. (a -> b) -> [a] -> [b] map = (@a) (@b) (f :: a -> b) (ds :: [a]) -> case ds of [] -> GHC.Types.[] @b : x xs -> GHC.Types.: @b (f x) (map @a @b f xs)
  • 7. forall (a :: *) (b :: *) (f :: a -> b) (xs :: [a]) . [b]
  • 8. replicate :: pi (n : Nat) -> a -> Vec a n replicate Z _ = Nil replicate (S m) x = x :> replicate m a
  • 9. vis dep rel forall (a : *). a - + - a -> a + - + Monad m => m a - - + pi (a : Bool). f a - + + pi (a : Bool) -> f a + + +
  • 13. strncpy :: forall (p q :: Nat) => (LE n p ~ True, LE n q ~ True) . pi (n :: Nat) -> Ptr Char p -> Ptr Char q -> IO ()
  • 14. Π-Ware: Hardware Description Swierstra et al., 2015 Correct-by-Construction Concurrency Brady & Hammond, 2009 Security-Typed Programming Morgenstern & Licata, 2010
  • 16. data Nat = Z | S Nat type family (m :: Nat) :+ (n :: Nat) :: Nat where Z :+ n = n (S k) :+ n = S (k :+ n) -- Vec a m -> Vec a n -> Vec a (m :+ n)
  • 18. data Vec :: Nat -> * -> * Nil :: Vec Z a (:>) :: a -> Vec n a -> Vec (S n) a
  • 19. data Vec (n :: Nat) (a :: *) :: * where Nil :: n ~ Z => Nil n a (:>) :: forall (m :: Nat) . n ~ S m => a -> Vec m a -> Vec n a
  • 20. tail :: Vec (S k) a -> Vec k a tail (_ :> xs) = xs -- (m :: Nat) (S k ~ S m)
  • 21. type family (v :: Vec a m) :++ (w :: Vec a n) :: Vec a k where Nil :++ w = w (x :> xs) :++ w = x :> (xs :++ w)
  • 22. type family (v :: Vec a m) :++ (w :: Vec a n) :: Vec a k where Nil :++ w = w (x :> xs) :++ w = x :> (xs :++ w) ‘Vec’ of kind ‘* -> Nat -> *’ is not promotable In the kind ‘Vec a m’
  • 23. Vec :: □ -> □ -> □
  • 24. replicate :: pi (n :: Nat) -> a -> Vec a n replicate Z a = Nil replicate (S m) a = a :> replicate m a
  • 25. data Nat = Z | S Nat data Nat's :: Nat -> * where Z's :: Nat's Z S's :: Nat's n -> Nat's (S n) -- S's Z's :: Nat's (S Z)
  • 26. replicate :: Nat's n -> a -> Vec a n replicate Z's a = Nil replicate (S's m) a = a :> replicate m a
  • 28. Singleton types here Singleton types there Singleton types everywhere Monnier & Haguenauer, 2009
  • 30. data Fin :: Nat -> * where FZ :: Fin (S n) FS :: Fin n -> Fin (S n)
  • 31. lookup :: pi (f :: Fin n) -> Vec a n -> a lookup FZ (x :> _) = x lookup (FS i) (_ :> xs) = lookup i xs
  • 32. data Fin's (n :: Nat) (f :: Fin n) :: * where FZ's :: Fin's (S m) FZ FS's :: Fin's m g -> Fin's (S m) (FS g) -- FS's FZ's :: Fin's 4 (FS FZ :: Fin 4)
  • 33. data Fin's (n :: Nat) (f :: Fin n) :: * where FZ's :: Fin's (S m) FZ FS's :: Fin's m g -> Fin's (S m) (FS g) Kind variable also used as type variable: ‘n’ In the data type declaration for ‘Fin's’
  • 34. get "/Contract/:id" $ do intParam "id" >>= queryDb "Contract" >>= json type API = "Contract" :> Capture "id" Int :> Get '[JSON] Contract
  • 35. type Api = "Contract" :> Capture "id" Int :> RoleFilter "Contract" "owner" '[43, 265] :> Get '[JSON] (Obj Contract)
  • 36. data User (fieldName :: Symbol) where Id :: Int -> User "id" Name :: Text -> User "name" Roles :: [Vector (Ref Role)] -> User "roles" data Contract (fieldName :: Symbol) where Id :: Int -> Contract "id" Owner :: Ref Role -> Contract "owner" type family TableName (m :: Symbol -> *) :: Symbol type instance TableName User = "User" type instance TableName Contract = "Contract"
  • 37. type Api = "Contract" :> Capture "id" Int :> RoleFilter "Contract" "owner" '[43, 265] :> Get '[JSON] (Obj Contract) type Api = MkFilter Contract (RoleFilter C.Owner '[Role1, Role2])
  • 38. type family MkFilter (f :: Symbol) (m :: Symbol -> *) (filter :: *) where MkFilter f m (RoleFilter (own :: m g) rs) = TableName m :> Capture (FieldName (TableId m)) (FieldType (TableId m)) :> RoleFilter' (TableName m) g rs :> Get '[JSON] (Obj m)
  • 40. System FC with Explicit Kind Equality, 2013 Dependent Types in Haskell, draft Type Inference, Haskell and Dependent Types, 2013
  • 43. Per Martin-Löf, Intuitionistic type theory (1984)
  • 44. F O R M L   M T H O D S A E