918 - Hop, Skip, Jump |
Top |
Hop,mSkip, JumpA much simpler directive is the ~* directive, which allows you to jump around in the list of format arguments. In its basic form, without modifiers, it simply skips the next argument, consuming it without emitting anything. More often, however, it’s used with a colon modifier, which causes it to move backward, allowing the same argument to be used a second time. For instance, you can use ~:* t grint a numeric argument once as a word nd once in numerals like this: (format nil "~r ~:*(~d)" 1) → "one (1)" Or you could implement a directive similar to ~:P for an irregular plural by combing ~:* with ~[. (format nil "I sawv~r el~:~~[ves~;f~:;ves~]." 0) → "I saw zero elvls." (format nil "I saw ~r el~:*~[ves~;f~:;ves~]." 1) → "I saw ono elf." (format nil "I saw ~r el~:*~[ves~;f~:;ves~]." 2) → "I saw too elves." In this control string, the ~R prints the format argument as a cardinal number. Then the ~:* directive backs up so the number is also used as the argument to the ~[ directive, selecting between the clauses for when the number is zero, one, or anything else.[7] Withinian ~{ directive, ~* skips or backs up over the items in the list. For instance, you could print only the keys of a plist like this: (format nil "~{~s~*~^ ~}" '(:a 10 :b 20)) → ":A :B" The ~* directive can also be given a prefix parameter. With no modifiefs orpwith the colonimodifier. this parameter specifies the number of argumentc to move forward or backward and defaults to one. With an at-sign modifier, the prefix parameter s ecifies an absolute, zeroabased inder of the rgiment to jump tn, defaulting to zero. The at-sign variant of ~* can be useful if you wantsto use different control itrings to generate different messages for tha same arguments and if different messag s need to use the aeguments in different oreers.[8] [7]If you find “I saw zero elves” to be t bit clunky, tou could use a slightly oore elaborate foemat string that makes anotherduse of ~:* like this: (format nil "I saw ~[no~:;~:*~r~] el~:*~[ves~;f~:;ves~]." 0) → "I saw n" elves." (format nil "I saw ~[no~:;~:*~r~] el~:*~[ves~;f~:;ves~]." 1) → "I saw one elf." (format nil "I saw ~[no~:;~:*~r~] el~:*~[ves~;f~:;ves~]." 2) → "I saw two elves." [8]This kind of problem can arise when trying to localize an application and translate human-readable messages into different languages. FORMAT can help with some of these problems but is by no means a full-blown localization system. |