Skip to content

Instantly share code, notes, and snippets.

@dullbananas
Last active April 11, 2020 18:51
Show Gist options
  • Save dullbananas/abbf4f630f2682b5b08e4b65faad896e to your computer and use it in GitHub Desktop.
Save dullbananas/abbf4f630f2682b5b08e4b65faad896e to your computer and use it in GitHub Desktop.
Elm extending `number` and `comparable` concept
module Fraction exposing (Fraction, create, toFloat_)
-- See https://discourse.elm-lang.org/t/proposal-extending-built-in-typeclasses/5510/2
type Fraction [ number, comparable ]
= Fraction Int Int
create : Int -> Int -> Fraction
create a b =
Fraction a b
toFloat_ : Fraction -> Float
toFloat_ ( Fraction a b ) =
( toFloat a ) / ( toFloat b )
-- ARITHMETIC
Fraction.(*) : Fraction -> Fraction -> Fraction
Fraction.(*) ( Fraction a1 b1 ) ( Fraction a2 b2 ) =
Fraction ( a1 * a2 ) ( b1 * b2 )
Fraction.(/) : Fraction -> Fraction -> Fraction
Fraction.(/) ( Fraction a1 b1 ) ( Fraction a2 b2 ) =
Fraction ( a1 * a2 ) ( b2 * b1 )
Fraction.(+) : Fraction -> Fraction -> Fraction
Fraction.(+) ( Fraction a1 b1 ) ( Fraction a2 b2 ) =
-- todo
Fraction.(-) : Fraction -> Fraction -> Fraction
Fraction.(-) ( Fraction a1 b1 ) ( Fraction a2 b2 ) =
-- todo
-- COMPARISON
Fraction.compare : Fraction -> Fraction -> Order
Fraction.compare f1 f2 =
compare ( toFloat_ f1 ) ( toFloat_ f2 )
import Fraction exposing (..)
-- Create fractions
f1 = create 3 1
f2 = create 1 2
-- Arithmetic operators can be used
f1 * f2 == create 3 2
f1 / f2 == create 6 1
-- ...
-- Comparison can be done
f1 > f2 == True
f1 < f2 == False
compare f1 f2 == GT
-- We can work with lists of fractions
List.maximum [ f1, f2 ] == Just f1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment