Jump to content

Long literals, with continuations: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 73:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V revdate = ‘2021-11-14’
 
V elements =
Line 97:
print(‘Last revision date: ’revdate)
print(‘Number of elements: ’items.len)
print(‘Last element : ’items.last)</langsyntaxhighlight>
 
{{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:
 
<langsyntaxhighlight lang="6502asm">HelloString:
db "Hello World" ;no null terminator
GoodbyeString:
db "Goodbye World!",0
 
PrintString HelloString ;unimplemented macro.</langsyntaxhighlight>
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.
 
<langsyntaxhighlight lang="6502asm">ElementNull:
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.</langsyntaxhighlight>
 
The required output can be obtained like so:
<langsyntaxhighlight lang="6502asm">LDA #<RevisionDate ;get the low byte of the address
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</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="6502asm">Elements_Lo:
db <hydrogen,<helium,<lithium,<beryllium,<boron,<carbon,<nitrogen,<oxygen,<fluorine,...
Elements_Hi:
db >hydrogen,>helium,>lithium,>beryllium,>boron,>carbon,>nitrogen,>oxygen,>fluorine,...</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="68000devpac">HelloString:
DC.B "Hello World" ;no null terminator
GoodbyeString:
Line 228:
EVEN
 
PrintString HelloString ;unimplemented macro.</langsyntaxhighlight>
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.
 
<langsyntaxhighlight lang="68000devpac">NullElement:
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.</langsyntaxhighlight>
 
The required output can be obtained like so:
<langsyntaxhighlight lang="68000devpac">LEA RevisionDate,A3 ; the printing routine uses A3 as input
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</langsyntaxhighlight>
 
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===
 
<langsyntaxhighlight lang="rebol">revDate: "2021-02-05"
elementString:
Line 352:
print ["Last revision date:" revDate]
print ["Number of elements:" size elements]
print ["Last element in list:" last elements]</langsyntaxhighlight>
 
{{out}}
Line 362:
===Using string blocks===
 
<langsyntaxhighlight lang="rebol">revDate: "2021-02-05"
elementString: {
Line 387:
print ["Last revision date:" revDate]
print ["Number of elements:" size elements]
print ["Last element in list:" last elements]</langsyntaxhighlight>
 
{{out}}
Line 396:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f LONG_LITERALS_WITH_CONTINUATIONS.AWK
BEGIN {
Line 493:
revised = "30JUN2020"
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 509:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
<lang BASIC256>
ultimaRevision$ = "2021-11-12"
arraybase 1
Line 518:
print "Last element : "; elemento$[elemento$[?]]
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 527:
=={{header|Crystal}}==
Crystal's <code>%w</code> literals create a whitespace-delimited array of strings at compile time
<langsyntaxhighlight lang="ruby">require "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}"</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 574:
{{libheader| System.StrUtils}}
{{Trans|Free Pascal}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Long_literals_with_continuations;
 
Line 613:
writeln(words[high(words)]);
readln;
end.</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="factor">USING: formatting kernel qw sequences ;
 
qw{
Line 665:
"Last revision: %s\n" printf
[ length ] [ last ] bi
"Number of elements: %d\nLast element: %s\n" printf</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="pascal">
program longStringLiteralDemo(output);
 
Line 716:
elementString, stdWordDelims));
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 726:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
Dim As String ultimaRevision = "2021-11-12"
Dim As String elemento(0 to ...) => { _
Line 753:
Print "Last element : "; elemento(Ubound(elemento))
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 763:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 821:
lix := strings.LastIndex(elements2, " ") // get index of last space
fmt.Println("Last element : ", elements2[lix+1:])
}</langsyntaxhighlight>
 
{{out}}
Line 832:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">elements = words "hydrogen \
\ fluorine neon sodium magnesium \
\ aluminum silicon phosphorous sulfur \
Line 860:
\ meitnerium darmstadtium roentgenium copernicium \
\ nihonium flerovium moscovium livermorium \
\ tennessine oganesson"</langsyntaxhighlight>
 
<pre>*Main> length elements
Line 931:
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq"># FOR FUTURE EDITORS:
# 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</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="julia">using Dates
 
# FOR FUTURE EDITORS:
Line 1,036:
 
report()
</langsyntaxhighlight> {{out}}
<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.
 
<langsyntaxhighlight lang="kotlin">import java.time.Instant
 
const val elementsChunk = """
Line 1,095:
println("Last element : ${elementsList.last()}")
println("The elements are : ${elementsList.joinToString(" ", limit = 5)}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,107:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">revised = "February 2, 2021"
-- 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," ")</langsyntaxhighlight>
{{out}}
<pre>revised date: February 2, 2021
Line 1,165:
 
===Using concatenations===
<langsyntaxhighlight Nimlang="nim">import strutils
 
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]</langsyntaxhighlight>
 
{{out}}
Line 1,203:
 
===Using a long literal string===
<langsyntaxhighlight Nimlang="nim">import strutils
 
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]</langsyntaxhighlight>
 
{{out}}
Line 1,263:
=={{header|Perl}}==
Mostly pointless...
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Long_literals,_with_continuations
Line 1,293:
element count: $count
last element: $last
END</langsyntaxhighlight>
{{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.
 
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
 
{{out}}
Line 1,357:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">elements$= "hydrogen helium lithium beryllium boron carbon " +
"nitrogen oxygen fluorine neon sodium magnesium " +
"aluminum silicon phosphorous sulfur chlorine argon " +
Line 1,385:
~"\nLast element: "+result$(nbf-1))
Input()
EndIf</langsyntaxhighlight>
{{out}}
<pre>Last revision: 2020-11-11
Line 1,393:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">"""Long string literal. Requires Python 3.6+ for f-strings."""
 
revision = "October 13th 2020"
Line 1,431:
if __name__ == "__main__":
report()
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,442:
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery">
<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>
</lang>
 
{{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" perl6line>my %periodic;
%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;</langsyntaxhighlight>
{{out}}
<pre>Revision date: 2020-03-23
Line 1,608:
 
Most modern REXXes have no practical limit for a clause length.
<langsyntaxhighlight lang="rexx">/*REXX pgm illustrates how to code a list of words (named chemical elements */
/*──────────────────────── 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*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 1,657:
 
The REXX version uses concatenation (also called abutment) to build the list.
<langsyntaxhighlight lang="rexx">/*REXX pgm illustrates how to code a list of words (named chemical elements */
/*──────────────────────── 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*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 1,697:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">elements = %w(
hydrogen helium lithium beryllium
boron carbon nitrogen oxygen
Line 1,732:
number of elements: #{elements.size}
last element: #{elements.last}"
</syntaxhighlight>
</lang>
{{out}}
<pre>Last mutation 2021-08-30 17:14:16 +0200
Line 1,740:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">(* space in \ .. \ is ignored *)
 
val elements = "\
Line 1,764:
\last element:\t" ^ List.last lst ^ "\n")
 
val () = report (String.fields (fn c => c = #" ") elements)</langsyntaxhighlight>
{{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).
<langsyntaxhighlight lang="tcl">set mtime "2021-05-10 16:11:50"
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]"</langsyntaxhighlight>
{{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">
<lang sh>
main() {
elements=(
Line 1,854:
printf 'Latest element: %s\n' "${elements[-1]}"
}
main "$@"</langsyntaxhighlight>
 
{{Out}}
Line 1,864:
 
The rows can begin in any column though, for a tidy display, we begin them all here in column 5.
<langsyntaxhighlight lang="ecmascript">import "/pattern" for Pattern
 
var elementStr =
Line 1,894:
System.print("Last updated : %(lastUpdate)")
System.print("Number of elements : %(elements.count)")
System.print("Last element : %(elements[-1])")</langsyntaxhighlight>
 
{{out}}
Line 1,911:
(by default). To turn that into one string with one space between each item,
use: elements.concat(" ")
<langsyntaxhighlight lang="zkl">revisionDate:="2020-03-23";
elements:=
#<<<"
Line 1,937:
#<<<
println("Revision date: ",revisionDate);
println(elements.len()," elements, the last being \"",elements[-1],"\"");</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.