SlideShare a Scribd company logo
Introducing dimensional: Statically Checked
Physical Dimensions for Haskell
Björn Buckwalter & Doug McClean
January 2016
Why Check Dimensions?
Why Check Dimensions?
The usual reasons:
Mars Climate Orbiter
Gimli Glider (Air Canada Flight 143)
Why Check Dimensions?
The usual reasons:
Mars Climate Orbiter
Gimli Glider (Air Canada Flight 143)
Both incidents involved more than just software, but you get the
idea.
Why Check Dimensions?
Types as Documentation
Type system requires source code documentation of units
where raw numeric values enter/leave the program
Existing Solutions
units (Richard Eisenberg)
uom-plugin (Adam Gundry)
dimensional-tf (Björn Buckwalter)
Why dimensional?
What Goodies Do We Have?
Types Reflect Dimensions, Not Units
Type-Level and Term-Level Dimensions
Strongly Kinded
What Goodies Do We Have?
Dimensional Arithmetic
Convenient Quantity Synonyms
type DLength = 'Dim 1 0 0 0 0 0 0 (morally)
type Length a = Quantity DLength a
type Capacitance a = ...
Pretty Printing
Choose display units with showIn
Show instance defaults to SI base units
Exact Conversion Factors Using exact-pi
What Goodies Do We Have?
Ultra-Minimal Dependencies
No Need for TH or Solver Plugins
Even to define new units
What Don’t We Have?
Custom dimensions or polymorphism over basis
What Don’t We Have?
Custom dimensions or polymorphism over basis
No frogs / square mile
What Don’t We Have?
Custom dimensions or polymorphism over basis
No frogs / square mile
You have to live with our decision not to encode angle as a
dimension, although doing so is potentially useful from an
engineering perspective
What Don’t We Have?
Custom dimensions or polymorphism over basis
No frogs / square mile
You have to live with our decision not to encode angle as a
dimension, although doing so is potentially useful from an
engineering perspective
CGS ESU units are treated as equivalents in SI basis
What Don’t We Have?
Torsors
No absolute temperatures, absolute times, etc.
See dimensional-dk-experimental
What Don’t We Have?
A Functor instance
Intentionally omitted, since it can be used to break
scale-invariance
What Don’t We Have?
A solid benchmark suite
Appropriate INLINE, SPECIALIZE, and RULES pragmas arising
from same
What Don’t We Have?
A type solver plugin, like Adam Gundry’s
It’s very useful for code that is heavily polymorphic in dimension.
For example, our attempts to build a usable dimensionally-typed
linear algebra library have been hampered by error messages of the
form:
Couldn't match type `((x / iv) / u) * u'
with `((x / iv) / x) * x'
I’m working on developing this, but could use some help.
Examples
Getting Started
cabal update
cabal install dimensional
Getting Started
Here’s an example word problem from the readme file:
A car travels at 60 kilometers per hour for one mile, at 50 kph for
one mile, at 40 kph for one mile, and at 30 kph for one mile.
How many minutes does the journey take?
What is the average speed of the car?
How many seconds does the journey take, rounded up to the
next whole second?
Readme Example Continued
{-# LANGUAGE NoImplicitPrelude #-}
module ReadmeExample where
import Numeric.Units.Dimensional.Prelude
import Numeric.Units.Dimensional.NonSI (mile)
Readme Example Continued
{-# LANGUAGE NoImplicitPrelude #-}
module ReadmeExample where
import Numeric.Units.Dimensional.Prelude
import Numeric.Units.Dimensional.NonSI (mile)
leg :: Length Double
leg = 1 *~ mile
Readme Example Continued
{-# LANGUAGE NoImplicitPrelude #-}
module ReadmeExample where
import Numeric.Units.Dimensional.Prelude
import Numeric.Units.Dimensional.NonSI (mile)
leg :: Length Double
leg = 1 *~ mile
speeds :: [Velocity Double]
speeds = [60, 50, 40, 30] *~~ (kilo meter / hour)
Readme Example Continued
timeOfJourney :: Time Double
timeOfJourney = sum $ fmap (leg /) speeds
Readme Example Continued
timeOfJourney :: Time Double
timeOfJourney = sum $ fmap (leg /) speeds
averageSpeed :: Velocity Double
averageSpeed = _4 * leg / timeOfJourney
-- = (4 *~ one) * leg / timeOfJourney
Readme Example Continued
timeOfJourney :: Time Double
timeOfJourney = sum $ fmap (leg /) speeds
averageSpeed :: Velocity Double
averageSpeed = _4 * leg / timeOfJourney
-- = (4 *~ one) * leg / timeOfJourney
wholeSeconds :: Integer
wholeSeconds = ceiling $ timeOfJourney /~ second
Reading Aircraft State from FlightGear
readState :: [Double] -> VehicleState'
readState [r, p, y, rDot, pDot, yDot, ax, ay, az, slip, as,
= VehicleState' { ... }
where
_orientation = quaternionFromTaitBryan (y *~ degree)
_orientationRate = quaternionFromTaitBryan (yDot *~ d
_velocity = (V3 vx vy vz) *~~ (foot / second)
_acceleration = (V3 ax ay az) *~~ (foot / second / se
_sideSlip = slip *~ degree
_airspeed = as *~ (nauticalMile / hour)
_altitudeMSL = msl *~ foot
_altitudeAGL = agl *~ foot
_location = GeodeticPlace . fromJust $ lat <°> lon
_elapsedTime = et *~ second
_propellerSpeed = rpm *~ (revolution / minute)
_staticPressure = statpres *~ inHg
_dynamicPressure = dynpres *~ (poundForce / square fo
Defining Custom Units
Internals
Ecosystem
dimensional-codata
CODATA Values (not to be confused with codata. . . )
Speed of light
Planck constant
etc.
exact-pi
data ExactPi = Exact Integer Rational
| Approximate (forall a.Floating a => a)
approximateValue :: Floating a => ExactPi -> a
Provides an exact representation of rational multiples of integer
powers of pi
exact-pi
data ExactPi = Exact Integer Rational
| Approximate (forall a.Floating a => a)
approximateValue :: Floating a => ExactPi -> a
Provides an exact representation of rational multiples of integer
powers of pi
Provides Num, Fractional, Floating instances which fall
back to Approximate where necessary
exact-pi
data ExactPi = Exact Integer Rational
| Approximate (forall a.Floating a => a)
approximateValue :: Floating a => ExactPi -> a
Provides an exact representation of rational multiples of integer
powers of pi
Provides Num, Fractional, Floating instances which fall
back to Approximate where necessary
Non-zero such numbers form a group under multiplication
exact-pi
data ExactPi = Exact Integer Rational
| Approximate (forall a.Floating a => a)
approximateValue :: Floating a => ExactPi -> a
Provides an exact representation of rational multiples of integer
powers of pi
Provides Num, Fractional, Floating instances which fall
back to Approximate where necessary
Non-zero such numbers form a group under multiplication
All exactly defined units we have encountered in practice have
an exact representation
exact-pi
data ExactPi = Exact Integer Rational
| Approximate (forall a.Floating a => a)
approximateValue :: Floating a => ExactPi -> a
Provides an exact representation of rational multiples of integer
powers of pi
Provides Num, Fractional, Floating instances which fall
back to Approximate where necessary
Non-zero such numbers form a group under multiplication
All exactly defined units we have encountered in practice have
an exact representation
Universal type of Approximate defers computations with pi,
+, etc. until after the desired result type has been selected.
igrf and atmos
We have dimensionally typed wrappers around some libraries that
provide physical information, for example
igrf, which implements the International Geomagnetic
Reference Field
atmos, which implements the 1976 International Standard
Atmosphere
Future Work
Forthcoming Version 1.1
Improved support for dynamic quantities
Forthcoming Version 1.1
Improved support for dynamic quantities
Improvements to unit names that are necessary for proper
parsing
Forthcoming Version 1.1
Improved support for dynamic quantities
Improvements to unit names that are necessary for proper
parsing
Fixed-point quantities (details on next slide)
Forthcoming Version 1.1
Improved support for dynamic quantities
Improvements to unit names that are necessary for proper
parsing
Fixed-point quantities (details on next slide)
User manual
Forthcoming Fixed-Point Support
data Variant = DQuantity
| DUnit Metricality
type Quantity = Dimensional DQuantity
Forthcoming Fixed-Point Support
data Variant = DQuantity
| DUnit Metricality
type Quantity = Dimensional DQuantity
becomes
data Variant = DQuantity ExactPi -- scale factor
| DUnit Metricality
type SQuantity s = Dimensional (DQuantity s)
type Quantity = SQuantity One
Forthcoming Fixed-Point Support
import qualified GHC.TypeLits as N
import qualified Data.ExactPi.TypeLevel as E
-- A dimensionless number with n fractional bits,
-- using a representation of type a.
type Q n a = SQuantity (E.One E./
(E.ExactNatural (2 N.^ n))) DOne a
Forthcoming Fixed-Point Support
import qualified GHC.TypeLits as N
import qualified Data.ExactPi.TypeLevel as E
-- A dimensionless number with n fractional bits,
-- using a representation of type a.
type Q n a = SQuantity (E.One E./
(E.ExactNatural (2 N.^ n))) DOne a
-- A single-turn angle represented as
-- a signed 16-bit integer.
type Angle16 = SQuantity (E.Pi E./
(E.ExactNatural (2 N.^ 15)))
DPlaneAngle Int16
Forthcoming Fixed-Point Support
import qualified GHC.TypeLits as N
import qualified Data.ExactPi.TypeLevel as E
-- A dimensionless number with n fractional bits,
-- using a representation of type a.
type Q n a = SQuantity (E.One E./
(E.ExactNatural (2 N.^ n))) DOne a
-- A single-turn angle represented as
-- a signed 16-bit integer.
type Angle16 = SQuantity (E.Pi E./
(E.ExactNatural (2 N.^ 15)))
DPlaneAngle Int16
fast_sin :: Angle16 -> Q 15 Int16
Forthcoming Fixed-Point Support
import qualified GHC.TypeLits as N
import qualified Data.ExactPi.TypeLevel as E
-- A dimensionless number with n fractional bits,
-- using a representation of type a.
type Q n a = SQuantity (E.One E./
(E.ExactNatural (2 N.^ n))) DOne a
-- A single-turn angle represented as
-- a signed 16-bit integer.
type Angle16 = SQuantity (E.Pi E./
(E.ExactNatural (2 N.^ 15)))
DPlaneAngle Int16
fast_sin :: Angle16 -> Q 15 Int16
With Template Haskell we can do even better tricks.
Forthcoming Fixed-Point Support
data VehicleState = VehicleState {
lat :: Angle32,
lon :: Angle32,
altitutde :: [exact| mm ] Int32,
vnorth :: [exact| cm / s ] Int16,
veast :: [exact| cm / s ] Int16,
vdown :: [exact| cm / s ] Int16,
elapsedTime :: [exact| ms ] Word32,
pressure :: [exact| 0.1 Pa ] Word32
}
The only holdup here is some remaining work on the parser.
Fixed-Point Arithmetic
(+), (-) :: (Num a) => SQuantity s d a
-> SQuantity s d a
-> SQuantity s d a
abs, negate :: (Num a) => SQuantity s d a
-> SQuantity s d a
epsilon :: (Integral a) => SQuantity s d a
_0 :: Num a => SQuantity s d a
pi :: (Integral a, E.KnownExactPi s) => SQuantity s DOne a
Fixed-Point Arithmetic
(*~) :: (RealFrac a, Integral b, E.MinCtxt s a)
=> a -> Unit m d a -> SQuantity s d b
Fixed-Point Arithmetic
(*~) :: (RealFrac a, Integral b, E.MinCtxt s a)
=> a -> Unit m d a -> SQuantity s d b
rescale :: (Integral a, Integral b,
E.KnownExactPi s1, E.KnownExactPi s2)
=> SQuantity s1 d a -> SQuantity s2 d b
Fixed-Point Arithmetic
(*~) :: (RealFrac a, Integral b, E.MinCtxt s a)
=> a -> Unit m d a -> SQuantity s d b
rescale :: (Integral a, Integral b,
E.KnownExactPi s1, E.KnownExactPi s2)
=> SQuantity s1 d a -> SQuantity s2 d b
rescaleVia :: (Integral a, Integral c,
RealFrac b, Floating b,
E.KnownExactPi s1, E.KnownExactPi s2)
=> Proxy b
-> SQuantity s1 d a -> SQuantity s2 d c
Linear Algebra
An n * m matrix doesn’t have n * m independent choices of
dimension, it only has n + m - 1. You can multiply A and B only
when the relationship between the dimensions of the columns of A is
the inverse of the relationship between the dimensions of the rows
of B.
We have a library that models this, but it isn’t particularly useful
without the typechecker plugin because only monomorphic uses of it
are checked.
If we can fix it up it will be very useful for control engineering
problems.
Contributing
Suggestions and pull requests are welcome.
Issue tracker and source repository are at:
https://github.com/bjornbm/dimensional
Questions

More Related Content

What's hot (20)

PDF
Acm aleppo cpc training ninth session
Ahmad Bashar Eter
 
PPT
Unit 4 functions and pointers
kirthika jeyenth
 
PPTX
Handling of character strings C programming
Appili Vamsi Krishna
 
PPT
Strings in c
vampugani
 
PDF
Acm aleppo cpc training second session
Ahmad Bashar Eter
 
PPTX
String C Programming
Prionto Abdullah
 
DOC
String in c
Suneel Dogra
 
PPT
Unit 5 structure and unions
kirthika jeyenth
 
PPTX
C programming - String
Achyut Devkota
 
PPTX
Analisa Expression pada after effect menggungakan bahasa script
VamelAfganisme Quartz
 
PPT
Strings
Nilesh Dalvi
 
PPT
String c
thirumalaikumar3
 
PPTX
String in c programming
Devan Thakur
 
PDF
Character Array and String
Tasnima Hamid
 
PPTX
Strings in C
Kamal Acharya
 
PDF
Strinng Classes in c++
Vikash Dhal
 
PPTX
C string
University of Potsdam
 
PPT
Strings
Imad Ali
 
PPTX
The string class
Syed Zaid Irshad
 
Acm aleppo cpc training ninth session
Ahmad Bashar Eter
 
Unit 4 functions and pointers
kirthika jeyenth
 
Handling of character strings C programming
Appili Vamsi Krishna
 
Strings in c
vampugani
 
Acm aleppo cpc training second session
Ahmad Bashar Eter
 
String C Programming
Prionto Abdullah
 
String in c
Suneel Dogra
 
Unit 5 structure and unions
kirthika jeyenth
 
C programming - String
Achyut Devkota
 
Analisa Expression pada after effect menggungakan bahasa script
VamelAfganisme Quartz
 
Strings
Nilesh Dalvi
 
String in c programming
Devan Thakur
 
Character Array and String
Tasnima Hamid
 
Strings in C
Kamal Acharya
 
Strinng Classes in c++
Vikash Dhal
 
Strings
Imad Ali
 
The string class
Syed Zaid Irshad
 

Viewers also liked (19)

DOC
Business
Li Jing
 
PPTX
Temas 3,4, 5 y 7
YenderRomero
 
PDF
Customer Service Certificate
Mahmoud Zaki
 
PDF
BSMP - Letter of Support
Mateus Lins Claudino
 
PDF
WHAT IS STEM? The Future is Here - San Antonio, Texas.
Jim "Brodie" Brazell
 
PDF
20141216_inrichtingsplan_sportpark_ijburg_webversie
Martijn ter Hoeve
 
PPTX
Quarter 1 lesson 4
EDLYN JOVEN
 
PPT
Social Media For Small Business
Nautic Studios
 
PPTX
Multisource feedback & its utility
IAMRAreval2015
 
PDF
FNC - AFRICAN CHORAL FESTIVAL FOR PEACE
josdiv
 
PPT
Вплив забруднення навколишнього середовища на статевий склад новонароджених
Taranoksana
 
PDF
Spotting an responding to institutional voids presentation
Ami Thomas
 
PPTX
Enhancing Twitter Data Analysis with Simple Semantic Filtering: Example in Tr...
Division of Biomedical Informatics, UC San Diego
 
PPTX
Unit 302 Powerpoint
Abigail_Dunne
 
PPTX
Kentro water purifier
Mohit Tripathi
 
DOCX
Romeo & juliet's plot
Rosa
 
DOCX
Electric potential numericals
manu jamwal
 
PDF
Key English Test- Cup 2 (book)
Anh Nguyen
 
PPTX
Preposition Usage
Preposition Checker
 
Business
Li Jing
 
Temas 3,4, 5 y 7
YenderRomero
 
Customer Service Certificate
Mahmoud Zaki
 
BSMP - Letter of Support
Mateus Lins Claudino
 
WHAT IS STEM? The Future is Here - San Antonio, Texas.
Jim "Brodie" Brazell
 
20141216_inrichtingsplan_sportpark_ijburg_webversie
Martijn ter Hoeve
 
Quarter 1 lesson 4
EDLYN JOVEN
 
Social Media For Small Business
Nautic Studios
 
Multisource feedback & its utility
IAMRAreval2015
 
FNC - AFRICAN CHORAL FESTIVAL FOR PEACE
josdiv
 
Вплив забруднення навколишнього середовища на статевий склад новонароджених
Taranoksana
 
Spotting an responding to institutional voids presentation
Ami Thomas
 
Enhancing Twitter Data Analysis with Simple Semantic Filtering: Example in Tr...
Division of Biomedical Informatics, UC San Diego
 
Unit 302 Powerpoint
Abigail_Dunne
 
Kentro water purifier
Mohit Tripathi
 
Romeo & juliet's plot
Rosa
 
Electric potential numericals
manu jamwal
 
Key English Test- Cup 2 (book)
Anh Nguyen
 
Preposition Usage
Preposition Checker
 
Ad

Similar to Introducing dimensional (20)

PDF
An Area Efficient Vedic-Wallace based Variable Precision Hardware Multiplier ...
IDES Editor
 
PPT
digital logic circuits, digital component floting and fixed point
Rai University
 
PDF
Gr2512211225
IJERA Editor
 
PDF
Gr2512211225
IJERA Editor
 
PDF
A Simple 3D Graphics Engine Written in Python and Allegro
snowfarthing
 
PDF
(Paper) Efficient Evaluation Methods of Elementary Functions Suitable for SIM...
Naoki Shibata
 
PPTX
IEEE-754 standard format to handle Floating-Point calculations in RISC-V CPUs...
zeeshanshanzy009
 
PDF
DESIGN OF DOUBLE PRECISION FLOATING POINT MULTIPLICATION ALGORITHM WITH VECTO...
jmicro
 
PDF
A Physical Units Library for the Next C++
Mateusz Pusz
 
PPTX
Adding Uncertainty and Units to Quantity Types in Software Models
Tanja Mayerhofer
 
PDF
Design and Analysis of High Performance Floating Point Arithmetic Unit
ijtsrd
 
PPTX
digital logic circuits, digital component floting and fixed point
Rai University
 
PDF
Chpater 6
EasyStudy3
 
PPTX
1.2 matlab numerical data
TANVIRAHMED611926
 
PDF
Jz2517611766
IJERA Editor
 
PDF
Jz2517611766
IJERA Editor
 
PPTX
B.sc cs-ii-u-1.8 digital logic circuits, digital component floting and fixed ...
Rai University
 
PDF
Scilab is not naive
Scilab
 
PDF
Scilabisnotnaive
zan
 
PPTX
Unit 2 Arithmetic
Balaji Vignesh
 
An Area Efficient Vedic-Wallace based Variable Precision Hardware Multiplier ...
IDES Editor
 
digital logic circuits, digital component floting and fixed point
Rai University
 
Gr2512211225
IJERA Editor
 
Gr2512211225
IJERA Editor
 
A Simple 3D Graphics Engine Written in Python and Allegro
snowfarthing
 
(Paper) Efficient Evaluation Methods of Elementary Functions Suitable for SIM...
Naoki Shibata
 
IEEE-754 standard format to handle Floating-Point calculations in RISC-V CPUs...
zeeshanshanzy009
 
DESIGN OF DOUBLE PRECISION FLOATING POINT MULTIPLICATION ALGORITHM WITH VECTO...
jmicro
 
A Physical Units Library for the Next C++
Mateusz Pusz
 
Adding Uncertainty and Units to Quantity Types in Software Models
Tanja Mayerhofer
 
Design and Analysis of High Performance Floating Point Arithmetic Unit
ijtsrd
 
digital logic circuits, digital component floting and fixed point
Rai University
 
Chpater 6
EasyStudy3
 
1.2 matlab numerical data
TANVIRAHMED611926
 
Jz2517611766
IJERA Editor
 
Jz2517611766
IJERA Editor
 
B.sc cs-ii-u-1.8 digital logic circuits, digital component floting and fixed ...
Rai University
 
Scilab is not naive
Scilab
 
Scilabisnotnaive
zan
 
Unit 2 Arithmetic
Balaji Vignesh
 
Ad

Recently uploaded (20)

PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PDF
AI Image Enhancer: Revolutionizing Visual Quality”
docmasoom
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PDF
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
PDF
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
PDF
Supabase Meetup: Build in a weekend, scale to millions
Carlo Gilmar Padilla Santana
 
PDF
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
PDF
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
What companies do with Pharo (ESUG 2025)
ESUG
 
PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PDF
Infrastructure planning and resilience - Keith Hastings.pptx.pdf
Safe Software
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PDF
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
PDF
Virtual Threads in Java: A New Dimension of Scalability and Performance
Tier1 app
 
PDF
How Agentic AI Networks are Revolutionizing Collaborative AI Ecosystems in 2025
ronakdubey419
 
PDF
How to Download and Install ADT (ABAP Development Tools) for Eclipse IDE | SA...
SAP Vista, an A L T Z E N Company
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
AI Image Enhancer: Revolutionizing Visual Quality”
docmasoom
 
Activate_Methodology_Summary presentatio
annapureddyn
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
Supabase Meetup: Build in a weekend, scale to millions
Carlo Gilmar Padilla Santana
 
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
What companies do with Pharo (ESUG 2025)
ESUG
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
Infrastructure planning and resilience - Keith Hastings.pptx.pdf
Safe Software
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
Virtual Threads in Java: A New Dimension of Scalability and Performance
Tier1 app
 
How Agentic AI Networks are Revolutionizing Collaborative AI Ecosystems in 2025
ronakdubey419
 
How to Download and Install ADT (ABAP Development Tools) for Eclipse IDE | SA...
SAP Vista, an A L T Z E N Company
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 

Introducing dimensional

  • 1. Introducing dimensional: Statically Checked Physical Dimensions for Haskell Björn Buckwalter & Doug McClean January 2016
  • 3. Why Check Dimensions? The usual reasons: Mars Climate Orbiter Gimli Glider (Air Canada Flight 143)
  • 4. Why Check Dimensions? The usual reasons: Mars Climate Orbiter Gimli Glider (Air Canada Flight 143) Both incidents involved more than just software, but you get the idea.
  • 5. Why Check Dimensions? Types as Documentation Type system requires source code documentation of units where raw numeric values enter/leave the program
  • 6. Existing Solutions units (Richard Eisenberg) uom-plugin (Adam Gundry) dimensional-tf (Björn Buckwalter)
  • 8. What Goodies Do We Have? Types Reflect Dimensions, Not Units Type-Level and Term-Level Dimensions Strongly Kinded
  • 9. What Goodies Do We Have? Dimensional Arithmetic Convenient Quantity Synonyms type DLength = 'Dim 1 0 0 0 0 0 0 (morally) type Length a = Quantity DLength a type Capacitance a = ... Pretty Printing Choose display units with showIn Show instance defaults to SI base units Exact Conversion Factors Using exact-pi
  • 10. What Goodies Do We Have? Ultra-Minimal Dependencies No Need for TH or Solver Plugins Even to define new units
  • 11. What Don’t We Have? Custom dimensions or polymorphism over basis
  • 12. What Don’t We Have? Custom dimensions or polymorphism over basis No frogs / square mile
  • 13. What Don’t We Have? Custom dimensions or polymorphism over basis No frogs / square mile You have to live with our decision not to encode angle as a dimension, although doing so is potentially useful from an engineering perspective
  • 14. What Don’t We Have? Custom dimensions or polymorphism over basis No frogs / square mile You have to live with our decision not to encode angle as a dimension, although doing so is potentially useful from an engineering perspective CGS ESU units are treated as equivalents in SI basis
  • 15. What Don’t We Have? Torsors No absolute temperatures, absolute times, etc. See dimensional-dk-experimental
  • 16. What Don’t We Have? A Functor instance Intentionally omitted, since it can be used to break scale-invariance
  • 17. What Don’t We Have? A solid benchmark suite Appropriate INLINE, SPECIALIZE, and RULES pragmas arising from same
  • 18. What Don’t We Have? A type solver plugin, like Adam Gundry’s It’s very useful for code that is heavily polymorphic in dimension. For example, our attempts to build a usable dimensionally-typed linear algebra library have been hampered by error messages of the form: Couldn't match type `((x / iv) / u) * u' with `((x / iv) / x) * x' I’m working on developing this, but could use some help.
  • 20. Getting Started cabal update cabal install dimensional
  • 21. Getting Started Here’s an example word problem from the readme file: A car travels at 60 kilometers per hour for one mile, at 50 kph for one mile, at 40 kph for one mile, and at 30 kph for one mile. How many minutes does the journey take? What is the average speed of the car? How many seconds does the journey take, rounded up to the next whole second?
  • 22. Readme Example Continued {-# LANGUAGE NoImplicitPrelude #-} module ReadmeExample where import Numeric.Units.Dimensional.Prelude import Numeric.Units.Dimensional.NonSI (mile)
  • 23. Readme Example Continued {-# LANGUAGE NoImplicitPrelude #-} module ReadmeExample where import Numeric.Units.Dimensional.Prelude import Numeric.Units.Dimensional.NonSI (mile) leg :: Length Double leg = 1 *~ mile
  • 24. Readme Example Continued {-# LANGUAGE NoImplicitPrelude #-} module ReadmeExample where import Numeric.Units.Dimensional.Prelude import Numeric.Units.Dimensional.NonSI (mile) leg :: Length Double leg = 1 *~ mile speeds :: [Velocity Double] speeds = [60, 50, 40, 30] *~~ (kilo meter / hour)
  • 25. Readme Example Continued timeOfJourney :: Time Double timeOfJourney = sum $ fmap (leg /) speeds
  • 26. Readme Example Continued timeOfJourney :: Time Double timeOfJourney = sum $ fmap (leg /) speeds averageSpeed :: Velocity Double averageSpeed = _4 * leg / timeOfJourney -- = (4 *~ one) * leg / timeOfJourney
  • 27. Readme Example Continued timeOfJourney :: Time Double timeOfJourney = sum $ fmap (leg /) speeds averageSpeed :: Velocity Double averageSpeed = _4 * leg / timeOfJourney -- = (4 *~ one) * leg / timeOfJourney wholeSeconds :: Integer wholeSeconds = ceiling $ timeOfJourney /~ second
  • 28. Reading Aircraft State from FlightGear readState :: [Double] -> VehicleState' readState [r, p, y, rDot, pDot, yDot, ax, ay, az, slip, as, = VehicleState' { ... } where _orientation = quaternionFromTaitBryan (y *~ degree) _orientationRate = quaternionFromTaitBryan (yDot *~ d _velocity = (V3 vx vy vz) *~~ (foot / second) _acceleration = (V3 ax ay az) *~~ (foot / second / se _sideSlip = slip *~ degree _airspeed = as *~ (nauticalMile / hour) _altitudeMSL = msl *~ foot _altitudeAGL = agl *~ foot _location = GeodeticPlace . fromJust $ lat <°> lon _elapsedTime = et *~ second _propellerSpeed = rpm *~ (revolution / minute) _staticPressure = statpres *~ inHg _dynamicPressure = dynpres *~ (poundForce / square fo
  • 32. dimensional-codata CODATA Values (not to be confused with codata. . . ) Speed of light Planck constant etc.
  • 33. exact-pi data ExactPi = Exact Integer Rational | Approximate (forall a.Floating a => a) approximateValue :: Floating a => ExactPi -> a Provides an exact representation of rational multiples of integer powers of pi
  • 34. exact-pi data ExactPi = Exact Integer Rational | Approximate (forall a.Floating a => a) approximateValue :: Floating a => ExactPi -> a Provides an exact representation of rational multiples of integer powers of pi Provides Num, Fractional, Floating instances which fall back to Approximate where necessary
  • 35. exact-pi data ExactPi = Exact Integer Rational | Approximate (forall a.Floating a => a) approximateValue :: Floating a => ExactPi -> a Provides an exact representation of rational multiples of integer powers of pi Provides Num, Fractional, Floating instances which fall back to Approximate where necessary Non-zero such numbers form a group under multiplication
  • 36. exact-pi data ExactPi = Exact Integer Rational | Approximate (forall a.Floating a => a) approximateValue :: Floating a => ExactPi -> a Provides an exact representation of rational multiples of integer powers of pi Provides Num, Fractional, Floating instances which fall back to Approximate where necessary Non-zero such numbers form a group under multiplication All exactly defined units we have encountered in practice have an exact representation
  • 37. exact-pi data ExactPi = Exact Integer Rational | Approximate (forall a.Floating a => a) approximateValue :: Floating a => ExactPi -> a Provides an exact representation of rational multiples of integer powers of pi Provides Num, Fractional, Floating instances which fall back to Approximate where necessary Non-zero such numbers form a group under multiplication All exactly defined units we have encountered in practice have an exact representation Universal type of Approximate defers computations with pi, +, etc. until after the desired result type has been selected.
  • 38. igrf and atmos We have dimensionally typed wrappers around some libraries that provide physical information, for example igrf, which implements the International Geomagnetic Reference Field atmos, which implements the 1976 International Standard Atmosphere
  • 40. Forthcoming Version 1.1 Improved support for dynamic quantities
  • 41. Forthcoming Version 1.1 Improved support for dynamic quantities Improvements to unit names that are necessary for proper parsing
  • 42. Forthcoming Version 1.1 Improved support for dynamic quantities Improvements to unit names that are necessary for proper parsing Fixed-point quantities (details on next slide)
  • 43. Forthcoming Version 1.1 Improved support for dynamic quantities Improvements to unit names that are necessary for proper parsing Fixed-point quantities (details on next slide) User manual
  • 44. Forthcoming Fixed-Point Support data Variant = DQuantity | DUnit Metricality type Quantity = Dimensional DQuantity
  • 45. Forthcoming Fixed-Point Support data Variant = DQuantity | DUnit Metricality type Quantity = Dimensional DQuantity becomes data Variant = DQuantity ExactPi -- scale factor | DUnit Metricality type SQuantity s = Dimensional (DQuantity s) type Quantity = SQuantity One
  • 46. Forthcoming Fixed-Point Support import qualified GHC.TypeLits as N import qualified Data.ExactPi.TypeLevel as E -- A dimensionless number with n fractional bits, -- using a representation of type a. type Q n a = SQuantity (E.One E./ (E.ExactNatural (2 N.^ n))) DOne a
  • 47. Forthcoming Fixed-Point Support import qualified GHC.TypeLits as N import qualified Data.ExactPi.TypeLevel as E -- A dimensionless number with n fractional bits, -- using a representation of type a. type Q n a = SQuantity (E.One E./ (E.ExactNatural (2 N.^ n))) DOne a -- A single-turn angle represented as -- a signed 16-bit integer. type Angle16 = SQuantity (E.Pi E./ (E.ExactNatural (2 N.^ 15))) DPlaneAngle Int16
  • 48. Forthcoming Fixed-Point Support import qualified GHC.TypeLits as N import qualified Data.ExactPi.TypeLevel as E -- A dimensionless number with n fractional bits, -- using a representation of type a. type Q n a = SQuantity (E.One E./ (E.ExactNatural (2 N.^ n))) DOne a -- A single-turn angle represented as -- a signed 16-bit integer. type Angle16 = SQuantity (E.Pi E./ (E.ExactNatural (2 N.^ 15))) DPlaneAngle Int16 fast_sin :: Angle16 -> Q 15 Int16
  • 49. Forthcoming Fixed-Point Support import qualified GHC.TypeLits as N import qualified Data.ExactPi.TypeLevel as E -- A dimensionless number with n fractional bits, -- using a representation of type a. type Q n a = SQuantity (E.One E./ (E.ExactNatural (2 N.^ n))) DOne a -- A single-turn angle represented as -- a signed 16-bit integer. type Angle16 = SQuantity (E.Pi E./ (E.ExactNatural (2 N.^ 15))) DPlaneAngle Int16 fast_sin :: Angle16 -> Q 15 Int16 With Template Haskell we can do even better tricks.
  • 50. Forthcoming Fixed-Point Support data VehicleState = VehicleState { lat :: Angle32, lon :: Angle32, altitutde :: [exact| mm ] Int32, vnorth :: [exact| cm / s ] Int16, veast :: [exact| cm / s ] Int16, vdown :: [exact| cm / s ] Int16, elapsedTime :: [exact| ms ] Word32, pressure :: [exact| 0.1 Pa ] Word32 } The only holdup here is some remaining work on the parser.
  • 51. Fixed-Point Arithmetic (+), (-) :: (Num a) => SQuantity s d a -> SQuantity s d a -> SQuantity s d a abs, negate :: (Num a) => SQuantity s d a -> SQuantity s d a epsilon :: (Integral a) => SQuantity s d a _0 :: Num a => SQuantity s d a pi :: (Integral a, E.KnownExactPi s) => SQuantity s DOne a
  • 52. Fixed-Point Arithmetic (*~) :: (RealFrac a, Integral b, E.MinCtxt s a) => a -> Unit m d a -> SQuantity s d b
  • 53. Fixed-Point Arithmetic (*~) :: (RealFrac a, Integral b, E.MinCtxt s a) => a -> Unit m d a -> SQuantity s d b rescale :: (Integral a, Integral b, E.KnownExactPi s1, E.KnownExactPi s2) => SQuantity s1 d a -> SQuantity s2 d b
  • 54. Fixed-Point Arithmetic (*~) :: (RealFrac a, Integral b, E.MinCtxt s a) => a -> Unit m d a -> SQuantity s d b rescale :: (Integral a, Integral b, E.KnownExactPi s1, E.KnownExactPi s2) => SQuantity s1 d a -> SQuantity s2 d b rescaleVia :: (Integral a, Integral c, RealFrac b, Floating b, E.KnownExactPi s1, E.KnownExactPi s2) => Proxy b -> SQuantity s1 d a -> SQuantity s2 d c
  • 55. Linear Algebra An n * m matrix doesn’t have n * m independent choices of dimension, it only has n + m - 1. You can multiply A and B only when the relationship between the dimensions of the columns of A is the inverse of the relationship between the dimensions of the rows of B. We have a library that models this, but it isn’t particularly useful without the typechecker plugin because only monomorphic uses of it are checked. If we can fix it up it will be very useful for control engineering problems.
  • 56. Contributing Suggestions and pull requests are welcome. Issue tracker and source repository are at: https://github.com/bjornbm/dimensional