elv-lib/mods/map.elv

82 lines
1.4 KiB
Plaintext

use ./common
use ./list
use ./num
fn is-empty {|m|
num:is-zero (count $m)
}
fn values {|m|
keys $m | each {|k| put $m[$k]}
}
fn pvalues {|m|
keys $m | peach {|k| put $m[$k]}
}
fn value-of {|m k &default=$nil|
common:cexec (has-key $m $k) { put $m[$k] } { put $default }
}
fn unzip {|m|
var keys values = [] []
keys $m | each {|k|
set @keys = $@keys $k
set @values = $@values $m[$k]
}
put $keys $values
}
fn zip {|keys values|
var ck cv = (count $keys) (count $values)
var c = (num:min [$ck $cv])
var m = [&]
range $c | peach {|i|
put [&k=$keys[$i] &v=$values[$i]]
} | each {|e|
set m[$e[k]] = $e[v]
}
put $m
}
fn to-map {|@argv|
var l = (list:-l $@argv)
zip [(list:indexes $l)] $l
}
fn to-set {|@argv|
var m = [&]
each {|k|
set m[$k] = $nil
} (list:-l $@argv)
put $m
}
fn mult-dissoc {|m @argv|
each {|k|
set m = (dissoc $m $k)
} $argv
put $m
}
fn mult-assoc {|&replace=$true m @argv|
each {|e|
var k v = $@e
if (or $replace (not (has-key $m $k))) {
set m = (assoc $m $k $v)
}
} $argv
put $m
}
fn add {|m k @values|
var values = (list:-l $values)
set m[$k] = (common:cexec (has-key $m $k) { put [(all $m[$k]) $@values ] } $values)
put $m
}
fn foreach {|cb @m|
set m = (common:cexec (list:is-empty $m) $one~ { put $m[0] })
keys $m | each {|k| put [$k $m[$k]]} | each {|e| $cb $@e}
}