Last active
May 27, 2021 23:13
-
-
Save thexa4/42acf7203cc3c426e6d2da939b22a66a to your computer and use it in GitHub Desktop.
KOS printf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function printf { | |
declare parameter format. | |
local sentinel to lex(). | |
local args to list(). | |
declare parameter last to sentinel. | |
local test to last. | |
until test = sentinel { | |
args:add(test). | |
declare parameter last to sentinel. | |
set test to last. | |
} | |
local replacements to lex(). | |
local parts to list(format). | |
for i in range(args:length) { | |
local flatmap to list(). | |
local placeholder to "{" + i + "}". | |
replacements:add(placeholder, args[i]). | |
for s in parts { | |
local splitted to s:split(placeholder). | |
flatmap:add(splitted[0]). | |
for i in range(1, splitted:length) { | |
flatmap:add(placeholder). | |
flatmap:add(splitted[i]). | |
} | |
} | |
set parts to flatmap. | |
} | |
local result to "". | |
for part in parts { | |
if replacements:haskey(part) { | |
set result to result + replacements[part]. | |
} else { | |
set result to result + part. | |
} | |
} | |
print(result). | |
} | |
printf("hello {0} world {1}", "foo", "bar", 4). | |
printf("{4} {1} {2} {0} {3}", "{2}", "bar", 4). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function printf { | |
declare parameter format. | |
local sentinel to lex(). | |
local args to queue(). | |
declare parameter last to sentinel. | |
local test to last. | |
until test = sentinel { | |
args:push(test). | |
declare parameter last to sentinel. | |
set test to last. | |
} | |
local parts to format:split("{}"). | |
local result to parts[0]. | |
for i in range(1, parts:length) { | |
if args:length > 0 | |
set result to result + args:pop() + parts[i]. | |
else | |
set result to result + "{}" + parts[i]. | |
} | |
print(result). | |
} | |
printf("hello {} world {}", "foo", "bar", 4). | |
printf("{} {} {} {} {}", "foo", "bar", 4). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment