Created
January 31, 2012 16:44
-
-
Save forki/1711508 to your computer and use it in GitHub Desktop.
Mimic type classes with additional param
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type 'a Num = { | |
zero: 'a | |
add: 'a -> 'a -> 'a | |
mult: 'a -> 'a -> 'a | |
fromInteger: int -> 'a } | |
let intNum = { | |
zero = 0 | |
add = (+) | |
mult = (*) | |
fromInteger = id } | |
let floatNum = { | |
zero = 0. | |
add = (+) | |
mult = (*) | |
fromInteger = float } | |
let square (d: 'a Num) x = d.mult x x | |
let sumofSquares (d: 'a Num) values = | |
values | |
|> Seq.map (square d) | |
|> Seq.fold d.add d.zero | |
let sumOfSquaresForInts = sumofSquares intNum | |
let sumOfSquaresForFloat = sumofSquares floatNum | |
let r1 = sumOfSquaresForInts [1;2;3] | |
let r2 = sumOfSquaresForFloat [1.1; 2.2; 3.1] | |
// type error | |
// let r3 = sumofSquares intNum [1.1;2.2;3.1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment