HELP: interpolate
{ $values { "str" string } }
{ $description "String interpolation using named variables and/or stack arguments, writing to the " { $link output-stream } "." }
-{ $notes "Stack arguments are numbered from the top of the stack." }
+{ $notes "Stack arguments are numbered from the top of the stack, or provided anonymously by order of arguments." }
{ $examples
{ $example
"USING: interpolate ;"
"\"Fred\" \"name\" [ \"Hi ${name}\" interpolate ] with-variable"
"Hi Fred"
}
+ { $example
+ "USING: interpolate ;"
+ "\"Mr.\" \"Anderson\"" "\"Hello, ${} ${}\" interpolate"
+ "Hello, Mr. Anderson"
+ }
} ;
HELP: interpolate>string
{ $values { "str" string } { "newstr" string } }
{ $description "String interpolation using named variables and/or stack arguments, captured as a " { $link string } "." }
-{ $notes "Stack arguments are numbered from the top of the stack." } ;
+{ $notes "Stack arguments are numbered from the top of the stack, or provided anonymously by order of arguments." } ;
{ interpolate interpolate>string } related-words
{ "A B" } [ "A" "B" "${1} ${0}" interpolate>string ] unit-test
{ "B A" } [ "A" "B" "${0} ${1}" interpolate>string ] unit-test
{ "C A" } [ "A" "B" "C" "${0} ${2}" interpolate>string ] unit-test
+{ "C B A" } [ "A" "B" "C" "${} ${1} ${2}" interpolate>string ] unit-test
{ "Hello, Jane." } [
"Jane" "name" set
"Mr." "${0} ${name}" interpolate>string
] unit-test
+{ "Hello, Mr. Anderson" } [
+ "Mr." "Anderson"
+ "Hello, ${} ${}" interpolate>string
+] unit-test
+
+{ "Mixing named and stack variables... stacks are cool!" } [
+ "cool!" "what" set
+ "named" "stack"
+ "Mixing ${} and ${} variables... ${0}s are ${what}"
+ interpolate>string
+] unit-test
+
{ "Sup Dawg, we heard you liked rims, so we put rims on your rims so you can roll while you roll." } [
"Dawg" "name" set
"rims" "noun" set
TUPLE: stack-var n ;
+TUPLE: anon-var ;
+
: (parse-interpolate) ( str -- )
[
"${" split1-slice [
"}" split1-slice
[
>string dup string>number
- [ stack-var boa ] [ named-var boa ] ?if ,
+ [ 1 + stack-var boa ]
+ [ [ anon-var new ] [ named-var boa ] if-empty ] ?if ,
]
[ (parse-interpolate) ] bi*
] when*
] bi*
] unless-empty ;
+: deanonymize ( seq -- seq' )
+ 0 over <reversed> [
+ dup anon-var? [
+ drop 1 + dup stack-var boa
+ ] when
+ ] map! 2drop ;
+
: parse-interpolate ( str -- seq )
- [ (parse-interpolate) ] { } make ;
+ [ (parse-interpolate) ] { } make deanonymize ;
: max-stack-var ( seq -- n/f )
f [
name>> quot call '[ _ @ present write ]
] [
dup stack-var? [
- n>> 1 + '[ _ npick present write ]
+ n>> '[ _ npick present write ]
] [
'[ _ write ]
] if
] map concat
vars [
- 1 + '[ _ ndrop ] append
+ '[ _ ndrop ] append
] when* ; inline
PRIVATE>