changeset 80:cbc92ee13f35

Add hash set
author Mike Pavone <pavone@retrodev.com>
date Mon, 16 Jul 2012 01:22:48 -0700
parents 7f635666c73d
children a905e13db753 3bf57ace3e0b 6f8d868e8da0
files modules/sets.tp samples/hashset.tp
diffstat 2 files changed, 104 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/modules/sets.tp	Mon Jul 16 01:22:48 2012 -0700
@@ -0,0 +1,80 @@
+#{
+	hash <- {
+		empty <- #{
+			empty? <- { true }
+		}
+		#{
+			buckets <- #[empty empty empty empty]
+			contains? <- :object {
+				hv <- object hash
+				
+				notdone <- true
+				hashes <- #[hv (hv + 1) (hv - 1)]
+				i <- 0
+				ret <- false
+				while: { if: notdone { i < 3 } } do: {
+					hv <- hashes get: i
+					trunc <- hv % (buckets length)
+					if: trunc < 0 { trunc <- 0 - trunc }
+					bucketval <- (buckets get: trunc)	
+					if: (bucketval empty?) {
+						notdone <- false
+					} else: {
+						if: (bucketval eq: hv) {
+							ret <- true
+							notdone <- false
+						}
+					}
+					i <- i + 1
+				}
+				ret
+			}
+			add <- :object {
+				addHash: (object hash)
+			}
+			addHash <- :hv {
+				makeBucket <- :hv {
+					#{
+						empty? <- { false }
+						v <- hv
+						eq <- :other { v = other }
+					}
+				}
+				notdone <- true
+				hashes <- #[hv (hv + 1) (hv - 1)]
+				i <- 0
+				while: { if: notdone { i < 3 } } do: {
+					hv <- hashes get: i
+					trunc <- hv % (buckets length)
+					if: trunc < 0 { trunc <- 0 - trunc }
+					bucketval <- (buckets get: trunc)	
+					if: (bucketval empty?) {
+						buckets set: trunc (makeBucket: hv)
+						notdone <- false
+					} else: {
+						if: (bucketval eq: hv) {
+							notdone <- false
+						}
+					}
+					i <- i + 1
+				}
+				if: notdone {
+					newsize <- (buckets length) * 3
+					newbucks <- #[]
+					while: { (newbucks length) < newsize } do: {
+						newbucks append: empty
+					}
+					oldbucks <- buckets
+					buckets <- newbucks
+					foreach: oldbucks :idx el {
+						if: (not: (el empty?)) {
+							addHash: (el v)
+						}
+					}
+					addHash: hv
+				}
+				self
+			}
+		}
+	}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/samples/hashset.tp	Mon Jul 16 01:22:48 2012 -0700
@@ -0,0 +1,24 @@
+#{
+	main <- {
+		inset <- #["foo" "bar" "foobar" 1 2 3]
+		notin <- #["baz" "qux" "bazqux" 4 5 6]
+		myset <- sets hash
+		foreach: inset :idx el {
+			myset add: el
+		}
+		foreach: inset :idx el {
+			if: (myset contains?: el) {
+				print: "set contains " . el . "\n"
+			} else: {
+				print: "set doesn't contain " . el . "\n"
+			}
+		}
+		foreach: notin :idx el {
+			if: (myset contains?: el) {
+				print: "set contains " . el . "\n"
+			} else: {
+				print: "set doesn't contain " . el . "\n"
+			}
+		}
+	}
+}