Created
February 9, 2012 19:41
-
-
Save mlhaufe/1782335 to your computer and use it in GitHub Desktop.
SML Vectors
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 vector = real list; | |
fun map2 (f1 : 'a * 'b -> 'c) (f2 : 'a -> 'c) (f3 : 'b -> 'c) (xs : 'a list) (ys : 'b list) = | |
let | |
fun m2 [] [] = [] | |
| m2 xs [] = f2 (hd xs) :: m2 (tl xs) [] | |
| m2 [] ys = f3 (hd ys) :: m2 [] (tl ys) | |
| m2 xs ys = f1 (hd xs, hd ys) :: m2 (tl xs) (tl ys) | |
in | |
m2 xs ys | |
end; | |
fun scale (x:real) (v:vector) :vector = map (fn n => x * n) v; | |
fun dot (v:vector) (w:vector) = foldr (op +) 0.0 ((map2 (op * ) (fn x => 0.0) (fn y => 0.0) v w)); | |
fun magn (v:vector) = Math.sqrt (dot v v); | |
fun add (v:vector) (w:vector) : vector = map2 (op +) (fn x => x) (fn y => y) v w | |
fun project w v = scale ((dot v w) / (dot w w)) w; | |
fun projectAll(S:vector list,v:vector):vector = | |
foldr (fn (a,b) => add a b) [0.0] (map (fn w => project w v) S); | |
fun residue [] v = v | |
| residue (S:(vector list)) (v:vector) = | |
let | |
val w1 = residue (tl S) (hd S) | |
in | |
residue (tl S) (add v (scale ~1.0 (project w1 v))) | |
end; | |
fun inSpan (S:vector list) (v:vector) = | |
let | |
val FUDGE = 0.000001 | |
in | |
magn (residue S v) < FUDGE | |
end; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment