Skip to content

Commit

Permalink
adding hash table literal syntax. closes issue #215.
Browse files Browse the repository at this point in the history
this took about 20 minutes
  • Loading branch information
JeffBezanson committed Oct 23, 2011
1 parent 90071ac commit 2d24d01
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 12 deletions.
14 changes: 14 additions & 0 deletions j/table.j
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,24 @@ type HashTable{K,V}
HashTable(n) = (n = _tablesz(n);
new(Array(K,n), Array(V,n), IntSet(n+1), IntSet(n+1),
identity))
function HashTable(ks::Tuple, vs::Tuple)
n = length(ks)
h = HashTable{K,V}(n)
for i=1:n
h[ks[i]] = vs[i]
end
return h
end
end
HashTable() = HashTable(0)
HashTable(n::Int) = HashTable{Any,Any}(n)

# syntax entry point
hashtable{K,V}(ks::(K...), vs::(V...)) = HashTable{K,V} (ks, vs)
hashtable{K} (ks::(K...), vs::Tuple ) = HashTable{K,Any} (ks, vs)
hashtable{V} (ks::Tuple , vs::(V...)) = HashTable{Any,V} (ks, vs)
hashtable (ks::Tuple , vs::Tuple) = HashTable{Any,Any}(ks, vs)

hashindex(key, sz) = (long(hash(key)) & (sz-1)) + 1

function rehash{K,V}(h::HashTable{K,V}, newsz)
Expand Down
36 changes: 24 additions & 12 deletions src/julia-syntax.scm
Original file line number Diff line number Diff line change
Expand Up @@ -707,18 +707,30 @@

;; cell array syntax
(pattern-lambda (cell1d . args)
(if (any (lambda (e) (and (pair? e) (eq? (car e) '...)))
args)
`(call (top cell_1d) ,@args)
(let ((name (gensy)))
`(block (= ,name (call (top Array) (top Any)
,(length args)))
,@(map (lambda (i elt)
`(call (top arrayset) ,name ,(+ 1 i)
,elt))
(iota (length args))
args)
,name))))
(cond ((any (lambda (e) (and (pair? e) (eq? (car e) '...)))
args)
`(call (top cell_1d) ,@args))
((any (lambda (e) (and (length= e 3)
(eq? (car e) '=>)))
args)
(if (not (every (lambda (e) (and (length= e 3)
(eq? (car e) '=>)))
args))
(error "invalid hash table literal")
`(call (top hashtable)
(tuple ,@(map cadr args))
(tuple ,@(map caddr args)))))
(else
(let ((name (gensy)))
`(block (= ,name (call (top Array) (top Any)
,(length args)))
,@(map (lambda (i elt)
`(call (top arrayset) ,name
,(+ 1 i)
,elt))
(iota (length args))
args)
,name)))))

(pattern-lambda (cell2d nr nc . args)
(if (any (lambda (e) (and (pair? e) (eq? (car e) '...)))
Expand Down

1 comment on commit 2d24d01

@StefanKarpinski
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So awesome. This is like Christmas. Goes a long way to make it feel more like other high-level languages without having to do much work.

Please sign in to comment.