RosettaCodeData/Task/Huffman-coding/Bracmat/huffman-coding.bracmat

57 lines
1.1 KiB
Plaintext

( "this is an example for huffman encoding":?S
& 0:?chars
& 0:?p
& ( @( !S
: ?
( [!p %?char [?p ?
& !char+!chars:?chars
& ~
)
)
|
)
& 0:?prioritized
& whl
' ( !chars:?n*%@?w+?chars
& (!n.!w)+!prioritized:?prioritized
)
& whl
' ( !prioritized:(?p.?x)+(?q.?y)+?nprioritized
& (!p+!q.(!p.0,!x)+(!q.1,!y))+!nprioritized:?prioritized
)
& 0:?L
& ( walk
= bits tree bit subtree
. !arg:(?bits.?tree)
& whl
' ( !tree:(?p.?bit,?subtree)+?tree
& ( !subtree:@
& (!subtree.str$(!bits !bit))+!L:?L
| walk$(!bits !bit.!subtree)
)
)
)
& !prioritized:(?.?prioritized)
& walk$(.!prioritized)
& lst$L
& :?encoded
& 0:?p
& ( @( !S
: ?
( [!p %?char [?p ?
& !L:?+(!char.?code)+?
& !encoded !code:?encoded
& ~
)
)
| out$(str$!encoded)
)
& ( decode
= char bits
. !L
: ?+(?char.?bits&@(!arg:!bits ?arg))+?
& !char decode$!arg
| !arg
)
& out$("decoded:" str$(decode$(str$!encoded)));