Long literals, with continuations: Difference between revisions
m
syntax highlighting fixup automation
Puppydrum64 (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 73:
{{trans|Python}}
<
V elements =
Line 97:
print(‘Last revision date: ’revdate)
print(‘Number of elements: ’items.len)
print(‘Last element : ’items.last)</
{{out}}
Line 109:
There is no need for continuation codes, as the language interprets a contiguous data block as a single entity, whether you intended it to be or not. If you had two consecutive strings embedded in the code and you forgot the null terminator on the first one, trying to print just the first string would print both. For example:
<
db "Hello World" ;no null terminator
GoodbyeString:
db "Goodbye World!",0
PrintString HelloString ;unimplemented macro.</
The output would be as follows, assuming the <code>PrintString</code> routine uses a null terminator to know when a string ends:
<pre>
Line 124:
Since each string is of variable length, it is much easier to make a lookup table of the elements ordered by atomic number, with each element in the lookup table being a pointer to the actual string consisting of that element's name.
<
dw nullString
Line 167:
; a constant value that cannot change at runtime.
; This counts the number of bytes between the two labels, and automatically adjusts when the size of the list changes.
; The division by 2 gets the actual element count since each address is 2 bytes long.</
The required output can be obtained like so:
<
STA z_L ;store it in z_L, a zero page memory address
LDA #>RevisionDate ;get the high byte
Line 202:
LDA ElementNull+1,x
STA z_H
JSR PrintString</
This routine can be expanded as new elements are discovered, but once the 128th element is discovered it will need to be reprogrammed since you can't offset more than x=255. This is actually a very simple fix, and can be accomplished by splitting the table as such:
<
db <hydrogen,<helium,<lithium,<beryllium,<boron,<carbon,<nitrogen,<oxygen,<fluorine,...
Elements_Hi:
db >hydrogen,>helium,>lithium,>beryllium,>boron,>carbon,>nitrogen,>oxygen,>fluorine,...</
Note that < and > are unary operators that mean "the low byte of" and "the high byte of", respectively. By storing the halves of each pointer in two separate tables, sharing a common index, we can index up to 256 elements rather than 128, without increasing the total data size of the tables.
Line 222:
There is no need for continuation codes, as the language interprets a contiguous data block as a single entity, whether you intended it to be or not. If you had two consecutive strings embedded in the code and you forgot the null terminator on the first one, trying to print just the first string would print both. For example:
<
DC.B "Hello World" ;no null terminator
GoodbyeString:
Line 228:
EVEN
PrintString HelloString ;unimplemented macro.</
The output would be as follows, assuming the <code>PrintString</code> routine uses a null terminator to know when a string ends:
<pre>
Line 238:
Since each string is of variable length, it is much easier to make a lookup table of the elements ordered by atomic number, with each element in the lookup table being a pointer to the actual string consisting of that element's name.
<
DC.L nullString
Elements:
Line 286:
; a constant value that cannot change at runtime.
; This counts the number of bytes between the two labels, and automatically adjusts when the size of the list changes.
; The division by 4 gets the actual element count since each address is 4 bytes long.</
The required output can be obtained like so:
<
JSR PrintString ; unimplemented printing routine
JSR NewLine ; unimplemented new line routine
Line 315:
MOVEA.L (A2,D1),A3
;dereference the pointer, offsetting by D1. This retrieves the address of the desired element in the list.
JSR PrintString</
This routine can easily be expanded for more elements. With a maximum offset of 16,383, it's unlikely that the table will get too large to properly index anytime soon.
Line 328:
===Using concatenations===
<
elementString:
Line 352:
print ["Last revision date:" revDate]
print ["Number of elements:" size elements]
print ["Last element in list:" last elements]</
{{out}}
Line 362:
===Using string blocks===
<
elementString: {
Line 387:
print ["Last revision date:" revDate]
print ["Number of elements:" size elements]
print ["Last element in list:" last elements]</
{{out}}
Line 396:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f LONG_LITERALS_WITH_CONTINUATIONS.AWK
BEGIN {
Line 493:
revised = "30JUN2020"
}
</syntaxhighlight>
{{out}}
<pre>
Line 509:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
ultimaRevision$ = "2021-11-12"
arraybase 1
Line 518:
print "Last element : "; elemento$[elemento$[?]]
end
</syntaxhighlight>
{{out}}
<pre>
Line 527:
=={{header|Crystal}}==
Crystal's <code>%w</code> literals create a whitespace-delimited array of strings at compile time
<
last_revision = Time.utc year: 2021, month: 2, day: 25
Line 568:
puts last_revision.to_s "last revised %B %e, %Y"
puts "number of elements: #{element_list.size}"
puts "highest element: #{element_list.last}"</
=={{header|Delphi}}==
Line 574:
{{libheader| System.StrUtils}}
{{Trans|Free Pascal}}
<syntaxhighlight lang="delphi">
program Long_literals_with_continuations;
Line 613:
writeln(words[high(words)]);
readln;
end.</
{{out}}
<pre>Last update: 2020-11-11
Line 626:
The convention in Factor is to limit lines to 64 characters wide if possible. This constraint is sometimes waived for large literals, but it was easy enough to accommodate here.
{{works with|Factor|0.99 2020-03-02}}
<
qw{
Line 665:
"Last revision: %s\n" printf
[ length ] [ last ] bi
"Number of elements: %d\nLast element: %s\n" printf</
{{out}}
<pre>
Line 677:
ANSI strings are pointers to sequences of characters.
The data type includes a reference count and a (4-Byte long) <tt>length</tt> field.
<
program longStringLiteralDemo(output);
Line 716:
elementString, stdWordDelims));
end.
</syntaxhighlight>
{{out}}
<pre>
Line 726:
=={{header|FreeBASIC}}==
<
Dim As String ultimaRevision = "2021-11-12"
Dim As String elemento(0 to ...) => { _
Line 753:
Print "Last element : "; elemento(Ubound(elemento))
Sleep
</syntaxhighlight>
{{out}}
<pre>
Line 763:
=={{header|Go}}==
<
import (
Line 821:
lix := strings.LastIndex(elements2, " ") // get index of last space
fmt.Println("Last element : ", elements2[lix+1:])
}</
{{out}}
Line 832:
=={{header|Haskell}}==
<
\ fluorine neon sodium magnesium \
\ aluminum silicon phosphorous sulfur \
Line 860:
\ meitnerium darmstadtium roentgenium copernicium \
\ nihonium flerovium moscovium livermorium \
\ tennessine oganesson"</
<pre>*Main> length elements
Line 931:
=={{header|jq}}==
<
# To add chemical elements, modify the CHEMICAL_ELEMENTS function,
# ensuring that the date is updated properly and that there is at least one
Line 972:
"Last element in list: \($a[-1])";
report</
Invocation: jq -nrf program.jq
{{out}}
Line 983:
The task does not as of the current revision mention lower versus upper case, but the below is corrected per a request anyway.
The task does ask to comment on which column code may start. The start column for code does not matter to Julia, or to most modern computer language compilers, other than in some cases (not string data) Python.
<
# FOR FUTURE EDITORS:
Line 1,036:
report()
</
<pre>
File last revised (formatted as dateTtime): 2020-03-24T02:48:55.421 GMT
Line 1,046:
Kotlin has raw string literals with <code>"""</code>. It does not (yet) have a native date/time library, so we use Java’s here.
<
const val elementsChunk = """
Line 1,095:
println("Last element : ${elementsList.last()}")
println("The elements are : ${elementsList.joinToString(" ", limit = 5)}")
}</
{{out}}
Line 1,107:
=={{header|Lua}}==
<
-- the long literal string is delimited by double square brackets: [[...]]
-- each word must be separated by at least one whitespace character
Line 1,156:
-- then, if still required, produce a single-space-between string version:
--finallist = table.concat(elements," ")</
{{out}}
<pre>revised date: February 2, 2021
Line 1,165:
===Using concatenations===
<
const RevDate = "2021-02-05"
Line 1,195:
echo "Last revision date: ", RevDate
echo "Number of elements: ", ElementList.len
echo "Last element in list: ", ElementList[^1]</
{{out}}
Line 1,203:
===Using a long literal string===
<
const RevDate = "2021-02-05"
Line 1,251:
echo "Last revision date: ", RevDate
echo "Number of elements: ", ElementList.len
echo "Last element in list: ", ElementList[^1]</
{{out}}
Line 1,263:
=={{header|Perl}}==
Mostly pointless...
<
use strict; # https://rosettacode.org/wiki/Long_literals,_with_continuations
Line 1,293:
element count: $count
last element: $last
END</
{{out}}
<pre>
Line 1,306:
You could also, like Julia, use get_file_date(command_line()[2]) instead of the hand-written last_updated constant. Phix code is free-format, indent things however you like, there is no specific maximum line length.
<!--<
<span style="color: #008080;">constant</span> <span style="color: #000000;">last_updated</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"March 24th, 2020"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">elements_text</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">`
Line 1,347:
"""</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">last_updated</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">elements</span><span style="color: #0000FF;">),</span><span style="color: #000000;">elements</span><span style="color: #0000FF;">[$]})</span>
<!--</
{{out}}
Line 1,357:
=={{header|PureBasic}}==
<
"nitrogen oxygen fluorine neon sodium magnesium " +
"aluminum silicon phosphorous sulfur chlorine argon " +
Line 1,385:
~"\nLast element: "+result$(nbf-1))
Input()
EndIf</
{{out}}
<pre>Last revision: 2020-11-11
Line 1,393:
=={{header|Python}}==
<
revision = "October 13th 2020"
Line 1,431:
if __name__ == "__main__":
report()
</syntaxhighlight>
{{out}}
Line 1,442:
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">
[ stack ] is last-revision ( --> $ )
$ "6 Jun 2021" last-revision put
Line 1,496:
say "Number of elements: " elementcount echo cr
say "Last element: " finalelement echo$ cr
</syntaxhighlight>
{{out}}
Line 1,513:
Not really sure I understand the point of this task. Seems to be load some list into memory and manipulate it somehow. Exceptionally boring to just read it in and then read it back out again. Perform some more interesting manipulations. Use < > quoting construct for literal string; unlimited (memory limited) characters, spaces don't matter, new-lines don't matter, blank lines don't matter.
<syntaxhighlight lang="raku"
%periodic<revision-date> = Date.new(2020,3,23);
%periodic<table> = |<
Line 1,587:
put 'Symbols for elements whose name starts with "P": ', %periodic<table>.grep( *.<name>.starts-with('P') )».<symbol>;
put "Elements with molecular weight between 20 & 40:\n ",%periodic<table>.grep( {+.<weight> ~~ Numeric and 20 < .<weight> < 40} )».<name>;
put "SCRN: ", %periodic<table>[87,17,92]».<symbol>.join.tclc;</
{{out}}
<pre>Revision date: 2020-03-23
Line 1,608:
Most modern REXXes have no practical limit for a clause length.
<
/*──────────────────────── ordered by their atomic number) in a list format. */
Line 1,639:
#= words(elements) /*the number of elements " " " */
say 'number of elements in the list: ' # /*show " " " " " " */
say 'the last element is: ' word($, #) /*stick a fork in it, we're all done*/</
{{out|output|text= when using the default input:}}
<pre>
Line 1,657:
The REXX version uses concatenation (also called abutment) to build the list.
<
/*──────────────────────── ordered by their atomic number) in a list format. */
Line 1,688:
#= words(elements) /*the number of elements " " " */
say 'number of elements in the list: ' # /*show " " " " " " */
say 'the last element is: ' word($, #) /*stick a fork in it, we're all done*/</
{{out|output|text= when using the default input:}}
<pre>
Line 1,697:
=={{header|Ruby}}==
<
hydrogen helium lithium beryllium
boron carbon nitrogen oxygen
Line 1,732:
number of elements: #{elements.size}
last element: #{elements.last}"
</syntaxhighlight>
{{out}}
<pre>Last mutation 2021-08-30 17:14:16 +0200
Line 1,740:
=={{header|Standard ML}}==
<
val elements = "\
Line 1,764:
\last element:\t" ^ List.last lst ^ "\n")
val () = report (String.fields (fn c => c = #" ") elements)</
{{out}}
<pre>revision date: 2021-02-25
Line 1,772:
=={{header|Tcl}}==
Using the neatly formatted table from other languages (can be reformatted easily using the non-standard utility column with option -t).
<
set elements {
hydrogen helium lithium beryllium
Line 1,809:
puts "Last modification time: $mtime"
puts "Number of elements: [llength $elements]"
puts "Last element: [lindex $elements end]"</
{{out}}
<pre>Last modification time: 2021-05-10 16:11:50
Line 1,824:
are sufficient to extend it across as many lines as needed:
<syntaxhighlight lang="sh">
main() {
elements=(
Line 1,854:
printf 'Latest element: %s\n' "${elements[-1]}"
}
main "$@"</
{{Out}}
Line 1,864:
The rows can begin in any column though, for a tidy display, we begin them all here in column 5.
<
var elementStr =
Line 1,894:
System.print("Last updated : %(lastUpdate)")
System.print("Number of elements : %(elements.count)")
System.print("Last element : %(elements[-1])")</
{{out}}
Line 1,911:
(by default). To turn that into one string with one space between each item,
use: elements.concat(" ")
<
elements:=
#<<<"
Line 1,937:
#<<<
println("Revision date: ",revisionDate);
println(elements.len()," elements, the last being \"",elements[-1],"\"");</
{{out}}
<pre>
|