Operations

Be sure to import spire’s implicits

import shapeless.syntax.singleton._
import spire.implicits._
import libra._, libra.implicits._

Addition

Here is how you add quantities:

(3.m + 2.m).show
// res0: String = "5 m [L]"

You can add quantities for any kind of number type, provided there’s an AdditiveSemigroup for them. Here we’re using spire’s rationals:

(r"1/3".m + r"2/3".m).show
// res1: String = "1 m [L]"

But you can only add quantities of the same dimension:

3.m + 4.kg
// error: These quantities can't be added!
// Most likely they have different dimensions.  If not, make sure that there's an implicit AdditiveSemigroup in scope.
// Left: libra.Quantity[Int,libra.Term[libra.Length,libra.Metre,libra.Fraction[Int(1),Int(1)]] :: shapeless.HNil]
// Right: libra.Quantity[Int,libra.Term[libra.Mass,libra.Kilogram,libra.Fraction[Int(1),Int(1)]] :: shapeless.HNil]
// 3.m + 4.kg
// ^^^^^^^^^^

Subtraction is just the same:

(3.m - 2.m).show
// res3: String = "1 m [L]"

Multiplication

Here’s how you multiply quantities:

(3.m * 2.kg).show
// res4: String = "6 m kg [L M]"

You can also divide quantities:

(3.0.m / 2.0.kg).show
// res5: String = "1.5 m kg^-1 [L M^-1]"

You can use euclidean division for discrete numbers:

(3.m /~ 2.kg).show
// res6: String = "1 m kg^-1 [L M^-1]"

Power

Here’s how you raise quantities to a power:

(3.0.m^(3.narrow)).show
// res7: String = "27.0 m^3 [L^3]"

Inverse

You can also invert quantities:

3.0.m.invert.show
// res8: String = "0.3333333333333333 m^-1 [L^-1]"

Scalar multiplication

You can multiply by scalar values:

(3.m :* 3).show
// res9: String = "9 m [L]"
(3 *: 3.m).show
// res10: String = "9 m [L]"

Extracting the base value

Here’s how you extract the value as a numeric in base units:

3.km.value
// res11: Int = 3