LZW compression: Difference between revisions

Content added Content deleted
Line 1,751: Line 1,751:
=={{header|EMal}}==
=={{header|EMal}}==
<syntaxhighlight lang="emal">
<syntaxhighlight lang="emal">
type LzwCompression
fun compress = List by text uncompressed
fun compress List by text uncompressed
Map dictionary = text%int[].with(256, <int i|text%int(chr(i) => i))
List output int[]
text w
text working ← Text.empty
List result = int[]
Map symbolTable text%int[].with(256, <int i|text%int(chr(i) => i))
for each text c in uncompressed
for each text c in uncompressed
text wc = w + c
text augmented working + c
if dictionary.has(wc)
if symbolTable.has(augmented)
w = wc
working augmented
else
else
symbolTable.insert(augmented, symbolTable.length)
result.append(dictionary[w])
int i ← symbolTable[working]
dictionary.insert(wc, dictionary.length)
output.append(i)
w = c
working ← c
end
end
end
end
if not w.isEmpty() do result.append(dictionary[w]) end
if not working.isEmpty()
int i ← symbolTable[working]
return result
output.append(i)
end
end
fun decompress = text by List compressed
return output
Map dictionary = int%text[].with(256, <int i|int%text(i => chr(i)))
end
text w = chr(compressed[0])
fun decompress text by List compressed
text result = *w
Map symbolTable int%text[].with(256, <int i|int%text(i => chr(i)))
for each int k in compressed.extract(1)
text working symbolTable[compressed[0]]
text entry
text output ← *working
if dictionary.has(k)
for each int i in compressed.extract(1)
entry = dictionary[k]
text s
else if k == dictionary.length
if symbolTable.has(i)
entry = w + w[0]
s ← symbolTable[i]
else if i æ symbolTable.length # cScSc problem
s ← working + working[0]
else
else
error(65, "Error decompressing")
error(65, "Error decompressing")
end
end
result.append(entry)
output.append(s)
dictionary.insert(dictionary.length, w + entry[0])
symbolTable.insert(symbolTable.length, working + s[0])
w = entry
working s
end
end
return result
return output
end
end
List compressed = compress("TOBEORNOTTOBEORTOBEORNOT")
List compressed = compress("TOBEORNOTTOBEORTOBEORNOT")