task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#OxygenBasic
OxygenBasic
    '========== Class Queue '==========   'FIRST IN FIRST OUT   bstring buf 'buffer to hold queue content int bg 'buffer base offset int i 'indexer int le 'length of buffer   method constructor() ==================== buf="" le=0 bg=0 i=0 end method   method destructor() =================== del buf le=0 bg=0 i=0 end method   method Encodelength(int ls) =========================== int p at (i+strptr buf) p=ls i+=sizeof int end method   method push(string s) ===================== int ls=len s if i+ls+8>le then buf+=nuls 8000+ls*2 'extend buf le=len buf end if EncodeLength ls 'length of input s mid buf,i+1,s 'append input s i+=ls end method   method popLength() as int ========================= if bg>=i then return -1 'buffer empty int p at (bg+strptr buf) bg+=sizeof int return p end method   method pop(string *s) as int ============================ int ls=popLength if ls<0 then s="" : return ls 'empty buffer s=mid buf,bg+1,ls bg+=ls 'cleanup buffer if bg>1e6 then buf=mid buf,bg+1 le=len buf i-=bg 'shrink buf bg=0 end if end method   method clear() ============== buf="" le=0 bg=0 i=0 end method   end class 'Queue     '==== 'DEMO '====   new Queue fifo string s ' fifo.push "HumptyDumpty" fifo.push "Sat on a wall" ' int er do er=fifo.pop s if er then print "(buffer empty)" : exit do print s loop   del fifo  
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#PureBasic
PureBasic
Structure Quaternion a.f b.f c.f d.f EndStructure   Procedure.f QNorm(*x.Quaternion) ProcedureReturn Sqr(Pow(*x\a, 2) + Pow(*x\b, 2) + Pow(*x\c, 2) + Pow(*x\d, 2)) EndProcedure   ;If supplied, the result is returned in the quaternion structure *res, ;otherwise a new quaternion is created. A pointer to the result is returned. Procedure QNeg(*x.Quaternion, *res.Quaternion = 0) If *res = 0: *res.Quaternion = AllocateMemory(SizeOf(Quaternion)): EndIf If *res *res\a = -*x\a *res\b = -*x\b *res\c = -*x\c *res\d = -*x\d EndIf ProcedureReturn *res EndProcedure   Procedure QConj(*x.Quaternion, *res.Quaternion = 0) If *res = 0: *res.Quaternion = AllocateMemory(SizeOf(Quaternion)): EndIf If *res *res\a = *x\a *res\b = -*x\b *res\c = -*x\c *res\d = -*x\d EndIf ProcedureReturn *res EndProcedure   Procedure QAddReal(r.f, *x.Quaternion, *res.Quaternion = 0) If *res = 0: *res.Quaternion = AllocateMemory(SizeOf(Quaternion)): EndIf If *res *res\a = *x\a + r *res\b = *x\b *res\c = *x\c *res\d = *x\d EndIf ProcedureReturn *res EndProcedure   Procedure QAddQuaternion(*x.Quaternion, *y.Quaternion, *res.Quaternion = 0) If *res = 0: *res.Quaternion = AllocateMemory(SizeOf(Quaternion)): EndIf If *res *res\a = *x\a + *y\a *res\b = *x\b + *y\b *res\c = *x\c + *y\c *res\d = *x\d + *y\d EndIf ProcedureReturn *res EndProcedure   Procedure QMulReal_and_Quaternion(r.f, *x.Quaternion, *res.Quaternion = 0) If *res = 0: *res.Quaternion = AllocateMemory(SizeOf(Quaternion)): EndIf If *res *res\a = *x\a * r *res\b = *x\b * r *res\c = *x\c * r *res\d = *x\d * r EndIf ProcedureReturn *res EndProcedure   Procedure QMulQuaternion(*x.Quaternion, *y.Quaternion, *res.Quaternion = 0) If *res = 0: *res.Quaternion = AllocateMemory(SizeOf(Quaternion)): EndIf If *res *res\a = *x\a * *y\a - *x\b * *y\b - *x\c * *y\c - *x\d * *y\d *res\b = *x\a * *y\b + *x\b * *y\a + *x\c * *y\d - *x\d * *y\c *res\c = *x\a * *y\c - *x\b * *y\d + *x\c * *y\a + *x\d * *y\b *res\d = *x\a * *y\d + *x\b * *y\c - *x\c * *y\b + *x\d * *y\a EndIf ProcedureReturn *res EndProcedure   Procedure Q_areEqual(*x.Quaternion, *y.Quaternion) If (*x\a <> *y\a) Or (*x\b <> *y\b) Or (*x\c <> *y\c) Or (*x\d <> *y\d) ProcedureReturn 0 ;false EndIf ProcedureReturn 1 ;true EndProcedure
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Go
Go
package main   import "fmt"   func main() { a := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\ta := %q\n\tfmt.Printf(a, a)\n}\n" fmt.Printf(a, a) }
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#PowerShell
PowerShell
  function range-extraction($arr) { if($arr.Count -gt 2) { $a, $b, $c, $arr = $arr $d = $e = $c if((($a + 1) -eq $b) -and (($b + 1) -eq $c)) { $test = $true while($arr -and $test) { $d = $e $e, $arr = $arr $test = ($d+1) -eq $e } if($test){"$a-$e"} elseif((-not $arr) -and $test){"$a-$d"} elseif(-not $arr){"$a-$d,$e"} else{"$a-$d," + (range-extraction (@($e)+$arr))} } elseif(($b + 1) -eq $c) {"$a," + (range-extraction (@($b, $c)+$arr))} else {"$a,$b," + (range-extraction (@($c)+$arr))} } else { switch($arr.Count) { 0 {""} 1 {"$arr"} 2 {"$($arr[0]),$($arr[1])"} } } } range-extraction @(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)  
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#XPL0
XPL0
int C; [repeat repeat C:= ChIn(1); \repeat until end-of-line ChOut(0, C); until C < $20; \CR, LF, or EOF until C = \EOF\ $1A; \repeat until end-of-file ]
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#zkl
zkl
foreach line in (File("foo.zkl")){print(line)}
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Symsyn
Symsyn
  | reverse string   c : 'abcdefghijklmnopqrstuvwxyz' d : ' '   c [] i #c j - j if i < j c.i d 1 c.j c.i 1 d c.j - j + i goif endif c []  
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Oz
Oz
declare fun {NewQueue} Stream WritePort = {Port.new Stream} ReadPos = {NewCell Stream} in WritePort#ReadPos end   proc {Push WritePort#_ Value} {Port.send WritePort Value} end   fun {Empty _#ReadPos} %% the queue is empty if the value at the current %% read position is not determined {Not {IsDet @ReadPos}} end   fun {Pop _#ReadPos} %% blocks if empty case @ReadPos of X|Xr then ReadPos := Xr X end end   Q = {NewQueue} in {Show {Empty Q}} {Push Q 42} {Show {Empty Q}} {Show {Pop Q}} {Show {Empty Q}}
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Python
Python
from collections import namedtuple import math   class Q(namedtuple('Quaternion', 'real, i, j, k')): 'Quaternion type: Q(real=0.0, i=0.0, j=0.0, k=0.0)'   __slots__ = ()   def __new__(_cls, real=0.0, i=0.0, j=0.0, k=0.0): 'Defaults all parts of quaternion to zero' return super().__new__(_cls, float(real), float(i), float(j), float(k))   def conjugate(self): return Q(self.real, -self.i, -self.j, -self.k)   def _norm2(self): return sum( x*x for x in self)   def norm(self): return math.sqrt(self._norm2())   def reciprocal(self): n2 = self._norm2() return Q(*(x / n2 for x in self.conjugate()))   def __str__(self): 'Shorter form of Quaternion as string' return 'Q(%g, %g, %g, %g)' % self   def __neg__(self): return Q(-self.real, -self.i, -self.j, -self.k)   def __add__(self, other): if type(other) == Q: return Q( *(s+o for s,o in zip(self, other)) ) try: f = float(other) except: return NotImplemented return Q(self.real + f, self.i, self.j, self.k)   def __radd__(self, other): return Q.__add__(self, other)   def __mul__(self, other): if type(other) == Q: a1,b1,c1,d1 = self a2,b2,c2,d2 = other return Q( a1*a2 - b1*b2 - c1*c2 - d1*d2, a1*b2 + b1*a2 + c1*d2 - d1*c2, a1*c2 - b1*d2 + c1*a2 + d1*b2, a1*d2 + b1*c2 - c1*b2 + d1*a2 ) try: f = float(other) except: return NotImplemented return Q(self.real * f, self.i * f, self.j * f, self.k * f)   def __rmul__(self, other): return Q.__mul__(self, other)   def __truediv__(self, other): if type(other) == Q: return self.__mul__(other.reciprocal()) try: f = float(other) except: return NotImplemented return Q(self.real / f, self.i / f, self.j / f, self.k / f)   def __rtruediv__(self, other): return other * self.reciprocal()   __div__, __rdiv__ = __truediv__, __rtruediv__   Quaternion = Q   q = Q(1, 2, 3, 4) q1 = Q(2, 3, 4, 5) q2 = Q(3, 4, 5, 6) r = 7
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Groovy
Groovy
s="s=%s;printf s,s.inspect()";printf s,s.inspect()
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Prolog
Prolog
range_extract :- L = [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39] , writeln(L), pack_Range(L, LP), maplist(study_Range, R, LP), extract_Range(LA, R), atom_chars(A, LA), writeln(A).     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % extract_Range(?In, ?Out) % In  : '-6,-3--1,3-5,7-11,14,15,17-20' => % Out : [-6], [-3--1], [3-5],[7-11], [14],[15], [17-20] % extract_Range([], []).     extract_Range(X , [Range | Y1]) :- get_Range(X, U-U, Range, X1), extract_Range(X1, Y1).       get_Range([], Range-[], Range, []). get_Range([','|B], Range-[], Range, B) :- !.   get_Range([A | B], EC, Range, R) :- append_dl(EC, [A | U]-U, NEC), get_Range(B, NEC, Range, R).     append_dl(X-Y, Y-Z, X-Z).   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % study Range(?In, ?Out) % In  : [-6] % Out : [-6,-6] % % In  : [-3--1] % Out : [-3, -1] % study_Range(Range1, [Deb, Deb]) :- catch(number_chars(Deb, Range1), Deb, false).   study_Range(Range1, [Deb, Fin]) :- append(A, ['-'|B], Range1), A \= [], number_chars(Deb, A), number_chars(Fin, B).   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % :- use_module(library(clpfd)). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Pack Range(?In, ?Out) % In  : -6, % Out : [-6] % % In  : -3, -2,-1 % Out : [-3,-1] % pack_Range([],[]).   pack_Range([X|Rest],[[X | V]|Packed]):- run(X,Rest, [X|V], RRest), pack_Range(RRest,Packed).       run(Fin,[Other|RRest], [Deb, Fin],[Other|RRest]):- Fin #\= Deb, Fin #\= Deb + 1, Other #\= Fin+1.   run(Fin,[],[_Var, Fin],[]).   run(Var,[Var1|LRest],[Deb, Fin], RRest):- Fin #\= Deb, Fin #\= Deb + 1, Var1 #= Var + 1, run(Var1,LRest,[Deb, Fin], RRest).   run(Val,[Other|RRest], [Val, Val],[Other|RRest]).  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Tailspin
Tailspin
  templates reverse '$:[ $... ] -> $(last..first:-1)...;' ! end reverse   'asdf' -> reverse -> !OUT::write   ' ' -> !OUT::write   'as⃝df̅' -> reverse -> !OUT::write  
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Pascal
Pascal
program fifo(input, output);   type pNode = ^tNode; tNode = record value: integer; next: pNode; end;   tFifo = record first, last: pNode; end;   procedure initFifo(var fifo: tFifo); begin fifo.first := nil; fifo.last := nil end;   procedure pushFifo(var fifo: tFifo; value: integer); var node: pNode; begin new(node); node^.value := value; node^.next := nil; if fifo.first = nil then fifo.first := node else fifo.last^.next := node; fifo.last := node end;   function popFifo(var fifo: tFifo; var value: integer): boolean; var node: pNode; begin if fifo.first = nil then popFifo := false else begin node := fifo.first; fifo.first := fifo.first^.next; value := node^.value; dispose(node); popFifo := true end end;   procedure testFifo; var fifo: tFifo; procedure testpop(expectEmpty: boolean; expectedValue: integer); var i: integer; begin if popFifo(fifo, i) then if expectEmpty then writeln('Error! Expected empty, got ', i, '.') else if i = expectedValue then writeln('Ok, got ', i, '.') else writeln('Error! Expected ', expectedValue, ', got ', i, '.') else if expectEmpty then writeln('Ok, fifo is empty.') else writeln('Error! Expected ', expectedValue, ', found fifo empty.') end; begin initFifo(fifo); pushFifo(fifo, 2); pushFifo(fifo, 3); pushFifo(fifo, 5); testpop(false, 2); pushFifo(fifo, 7); testpop(false, 3); testpop(false, 5); pushFifo(fifo, 11); testpop(false, 7); testpop(false, 11); pushFifo(fifo, 13); testpop(false, 13); testpop(true, 0); pushFifo(fifo, 17); testpop(false, 17); testpop(true, 0) end;   begin writeln('Testing fifo implementation ...'); testFifo; writeln('Testing finished.') end.
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#R
R
  library(quaternions)   q <- Q(1, 2, 3, 4) q1 <- Q(2, 3, 4, 5) q2 <- Q(3, 4, 5, 6) r <- 7.0   display <- function(x){ e <- deparse(substitute(x)) res <- if(class(x) == "Q") paste(x$r, "+", x$i, "i+", x$j, "j+", x$k, "k", sep = "") else x cat(noquote(paste(c(e, " = ", res, "\n"), collapse=""))) invisible(res) }   display(norm(q)) display(-q) display(Conj(q)) display(r + q) display(q1 + q2) display(r*q) display(q*r) if(display(q1*q2) == display(q2*q1)) cat("q1*q2 == q2*q1\n") else cat("q1*q2 != q2*q1\n")   ## norm(q) = 5.47722557505166 ## -q = -1+-2i+-3j+-4k ## Conj(q) = 1+-2i+-3j+-4k ## r + q = 8+2i+3j+4k ## q1 + q2 = 5+7i+9j+11k ## r * q = 7+14i+21j+28k ## q * r = 7+14i+21j+28k ## q1 * q2 = -56+16i+24j+26k ## q2 * q1 = -56+18i+20j+28k ## q1*q2 != q2*q1    
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#GW-BASIC
GW-BASIC
10 LIST
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Hare
Hare
use fmt; const src: str = "use fmt; const src: str = {0}{1}{0}; export fn main() void = {{fmt::printfln(src, '{0}', src)!;}};"; export fn main() void = {fmt::printfln(src, '"', src)!;};
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#PureBasic
PureBasic
DataSection Data.i 33 ;count of elements to be read Data.i 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 Data.i 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 EndDataSection   NewList values() ;setup list Define elementCount, i Read.i elementCount For i = 1 To elementCount AddElement(values()): Read.i values() Next   Procedure.s rangeExtract(List values()) Protected listSize = ListSize(values()) - 1 Protected rangeMarker, rangeStart, rangeIncrement, retraceSteps, rangeSize, endOfRange, output.s, sub.s   ForEach values() rangeStart = values(): sub = Str(rangeStart) If NextElement(values()) retraceSteps = 1 rangeIncrement = values() - rangeStart If rangeIncrement = 1 Or rangeIncrement = -1 ;found start of possible range If ListIndex(values()) <> listSize retraceSteps = 2 rangeSize = 2 endOfRange = #False rangeMarker = values() While NextElement(values()) If values() - rangeMarker <> rangeIncrement endOfRange = #True Break EndIf rangeSize + 1 rangeMarker = values() Wend   If rangeSize > 2 sub = Str(rangeStart) + "-" + Str(rangeMarker) If Not endOfRange retraceSteps = 0 ;at end of list Else retraceSteps = 1 EndIf EndIf EndIf EndIf   ;return to the value before look-aheads While retraceSteps > 0 PreviousElement(values()): retraceSteps - 1 Wend EndIf   output + sub + "," Next   ProcedureReturn RTrim(output, ",") EndProcedure   If OpenConsole() PrintN(rangeExtract(values()))   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Tcl
Tcl
package require Tcl 8.5 string reverse asdf
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Perl
Perl
use Carp; sub mypush (\@@) {my($list,@things)=@_; push @$list, @things} sub mypop (\@) {my($list)=@_; @$list or croak "Empty"; shift @$list } sub empty (@) {not @_}
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Racket
Racket
#lang racket   (struct quaternion (a b c d) #:transparent)   (define-match-expander quaternion: (λ (stx) (syntax-case stx () [(_ a b c d) #'(or (quaternion a b c d) (and a (app (λ(_) 0) b) (app (λ(_) 0) c) (app (λ(_) 0) d)))])))   (define (norm q) (match q [(quaternion: a b c d) (sqrt (+ (sqr a) (sqr b) (sqr c) (sqr d)))]))   (define (negate q) (match q [(quaternion: a b c d) (quaternion (- a) (- b) (- c) (- d))]))   (define (conjugate q) (match q [(quaternion: a b c d) (quaternion a (- b) (- c) (- d))]))   (define (add q1 q2 . q-rest) (let ((ans (match* (q1 q2) [((quaternion: a1 b1 c1 d1) (quaternion: a2 b2 c2 d2)) (quaternion (+ a1 a2) (+ b1 b2) (+ c1 c2) (+ d1 d2))]))) (if (empty? q-rest) ans (apply add (cons ans q-rest)))))   (define (multiply q1 q2 . q-rest) (let ((ans (match* (q1 q2) [((quaternion: a1 b1 c1 d1) (quaternion: a2 b2 c2 d2)) (quaternion (- (* a1 a2) (* b1 b2) (* c1 c2) (* d1 d2)) (+ (* a1 b2) (* b1 a2) (* c1 d2) (- (* d1 c2))) (+ (* a1 c2) (- (* b1 d2)) (* c1 a2) (* d1 b2)) (+ (* a1 d2) (* b1 c2) (- (* c1 b2)) (* d1 a2)))]))) (if (empty? q-rest) ans (apply multiply (cons ans q-rest)))))   ;; Tests (module+ main (define i (quaternion 0 1 0 0)) (define j (quaternion 0 0 1 0)) (define k (quaternion 0 0 0 1)) (displayln (multiply i j k)) (newline)   (define q (quaternion 1 2 3 4)) (define q1 (quaternion 2 3 4 5)) (define q2 (quaternion 3 4 5 6)) (define r 7)   (for ([quat (list q q1 q2)]) (displayln quat) (displayln (norm quat)) (displayln (negate quat)) (displayln (conjugate quat)) (newline))   (add r q) (add q1 q2) (multiply r q)   (newline) (multiply q1 q2) (multiply q2 q1) (equal? (multiply q1 q2) (multiply q2 q1)))
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Haskell
Haskell
let q s = putStrLn (s ++ show s) in q "let q s = putStrLn (s ++ show s) in q "
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Python
Python
def range_extract(lst): 'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints' lenlst = len(lst) i = 0 while i< lenlst: low = lst[i] while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1 hi = lst[i] if hi - low >= 2: yield (low, hi) elif hi - low == 1: yield (low,) yield (hi,) else: yield (low,) i += 1   def printr(ranges): print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r) for r in ranges ) )   if __name__ == '__main__': for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20], [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]: #print(list(range_extract(lst))) printr(range_extract(lst))
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#TI-83_BASIC
TI-83 BASIC
:Str1 :For(I,1,length(Ans)-1 :sub(Ans,2I,1)+Ans :End :sub(Ans,1,I→Str1
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Phix
Phix
with javascript_semantics sequence queue = {} procedure push_item(object what) queue = append(queue,what) end procedure function pop_item() object what = queue[1] queue = queue[2..$] return what end function function empty() return length(queue)=0 end function
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Raku
Raku
class Quaternion { has Real ( $.r, $.i, $.j, $.k );   multi method new ( Real $r, Real $i, Real $j, Real $k ) { self.bless: :$r, :$i, :$j, :$k; } multi qu(*@r) is export { Quaternion.new: |@r } sub postfix:<j>(Real $x) is export { qu 0, 0, $x, 0 } sub postfix:<k>(Real $x) is export { qu 0, 0, 0, $x }   method Str () { "$.r + {$.i}i + {$.j}j + {$.k}k" } method reals () { $.r, $.i, $.j, $.k } method conj () { qu $.r, -$.i, -$.j, -$.k } method norm () { sqrt [+] self.reals X** 2 }   multi infix:<eqv> ( Quaternion $a, Quaternion $b ) is export { $a.reals eqv $b.reals }   multi infix:<+> ( Quaternion $a, Real $b ) is export { qu $b+$a.r, $a.i, $a.j, $a.k } multi infix:<+> ( Real $a, Quaternion $b ) is export { qu $a+$b.r, $b.i, $b.j, $b.k } multi infix:<+> ( Quaternion $a, Complex $b ) is export { qu $b.re + $a.r, $b.im + $a.i, $a.j, $a.k } multi infix:<+> ( Complex $a, Quaternion $b ) is export { qu $a.re + $b.r, $a.im + $b.i, $b.j, $b.k } multi infix:<+> ( Quaternion $a, Quaternion $b ) is export { qu $a.reals Z+ $b.reals }   multi prefix:<-> ( Quaternion $a ) is export { qu $a.reals X* -1 }   multi infix:<*> ( Quaternion $a, Real $b ) is export { qu $a.reals X* $b } multi infix:<*> ( Real $a, Quaternion $b ) is export { qu $b.reals X* $a } multi infix:<*> ( Quaternion $a, Complex $b ) is export { $a * qu $b.reals, 0, 0 } multi infix:<*> ( Complex $a, Quaternion $b ) is export { $b R* qu $a.reals, 0, 0 }   multi infix:<*> ( Quaternion $a, Quaternion $b ) is export { my @a_rijk = $a.reals; my ( $r, $i, $j, $k ) = $b.reals; return qu [+]( @a_rijk Z* $r, -$i, -$j, -$k ), # real [+]( @a_rijk Z* $i, $r, $k, -$j ), # i [+]( @a_rijk Z* $j, -$k, $r, $i ), # j [+]( @a_rijk Z* $k, $j, -$i, $r ); # k } } import Quaternion;   my $q = 1 + 2i + 3j + 4k; my $q1 = 2 + 3i + 4j + 5k; my $q2 = 3 + 4i + 5j + 6k; my $r = 7;   say "1) q norm = {$q.norm}"; say "2) -q = {-$q}"; say "3) q conj = {$q.conj}"; say "4) q + r = {$q + $r}"; say "5) q1 + q2 = {$q1 + $q2}"; say "6) q * r = {$q * $r}"; say "7) q1 * q2 = {$q1 * $q2}"; say "8) q1q2 { $q1 * $q2 eqv $q2 * $q1 ?? '==' !! '!=' } q2q1";
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Hoon
Hoon
!:  :-  %say |= [^ [~ ~]] =+ ^= s ((list ,@tas) ~['!:  :-  %say |= [^ [~ ~]] =+ ^= s ((list ,@tas) ~[' 'x' '])  :-  %noun (,tape (turn s |=(a=@tas ?:(=(a %x) (crip `(list ,@tas)`(turn s |=(b=@tas =+([s=?:(=(b %x) " " "") m=(trip ~~~27.)] (crip :(welp s m (trip b) m s)))))) a))))'])  :-  %noun (,tape (turn s |=(a=@tas ?:(=(a %x) (crip `(list ,@tas)`(turn s |=(b=@tas =+([s=?:(=(b %x) " " "") m=(trip ~~~27.)] (crip :(welp s m (trip b) m s)))))) a))))
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Qi
Qi
  (define make-range Start Start -> ["," Start] Start End -> ["," Start "," End] where (= End (+ Start 1)) Start End -> ["," Start "-" End])   (define range-extract-0 Start End [] -> (make-range Start End) Start End [A|As] -> (range-extract-0 Start A As) where (= (+ 1 End) A) Start End [A|As] -> (append (make-range Start End) (range-extract-0 A A As)))   (define range-extract [A |As] -> (FORMAT NIL "~{~a~}" (tail (range-extract-0 A A As))))   (range-extract [ 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39])  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#TMG
TMG
prog: parse(str); str: smark any(!<<>>) scopy str/done = { 1 2 }; done:  ;
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def push /# l i -- l&i #/ 0 put enddef   def empty? /# l -- flag #/ len 0 == enddef   def pop /# l -- l-1 #/ empty? if "Empty" else head swap tail nip swap endif enddef     ( ) /# empty queue #/   1 push 2 push 3 push pop ? pop ? pop ? pop ?
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Red
Red
  quaternion: context [ quaternion!: make typeset! [block! hash! vector!] multiply: function [q [integer! float! quaternion!] p [integer! float! quaternion!]][ case [ number? q [collect [forall p [keep p/1 * q]]] number? p [collect [forall q [keep q/1 * p]]] 'else [ reduce [ (q/1 * p/1) - (q/2 * p/2) - (q/3 * p/3) - (q/4 * p/4) (q/1 * p/2) + (q/2 * p/1) + (q/3 * p/4) - (q/4 * p/3) (q/1 * p/3) + (q/3 * p/1) + (q/4 * p/2) - (q/2 * p/4) (q/1 * p/4) + (q/4 * p/1) + (q/2 * p/3) - (q/3 * p/2) ] ] ] ] add: func [q [integer! float! quaternion!] p [integer! float! quaternion!]][ case [ number? q [head change copy p p/1 + q] number? p [head change copy q q/1 + p] 'else [collect [forall q [keep q/1 + p/(index? q)]]] ] ] negate: func [q [quaternion!]][collect [forall q [keep 0 - q/1]]] conjugate: func [q [quaternion!]][collect [keep q/1 q: next q forall q [keep 0 - q/1]]] norm: func [q [quaternion!]][sqrt first multiply q conjugate copy q] normalize: function [q [quaternion!]][n: norm q collect [forall q [keep q/1 / n]]] inverse: func [q [quaternion!]][(conjugate q) / ((norm q) ** 2)] ]   set [q q1 q2 r] [[1 2 3 4] [2 3 4 5] [3 4 5 6] 7]   print [{ 1. The norm of a quaternion: `quaternion/norm q` =>} quaternion/norm q {   2. The negative of a quaternion: `quaternion/negate q` =>} mold quaternion/negate q {   3. The conjugate of a quaternion: <code>quaternion/conjugate q</code> =>} mold quaternion/conjugate q {   4. Addition of a real number `r` and a quaternion `q`: `quaternion/add r q` =>} mold quaternion/add r q { `quaternion/add q r` =>} mold quaternion/add q r {   5. Addition of two quaternions: `quaternion/add q1 q2` =>} mold quaternion/add q1 q2 {   6. Multiplication of a real number and a quaternion: `quaternion/multiply q r` =>} mold quaternion/multiply q r { `quaternion/multiply r q` =>} mold quaternion/multiply r q {   7. Multiplication of two quaternions `q1` and `q2` is given by: `quaternion/multiply q1 q2` =>} mold quaternion/multiply q1 q2 {   8. Show that, for the two quaternions `q1` and `q2`: `equal? quaternion/multiply q1 q2 mold quaternion/multiply q2 q1` =>} equal? quaternion/multiply q1 q2 quaternion/multiply q2 q1]  
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#HQ9.2B
HQ9+
Q
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#R
R
extract.range = function(v) { r <- c(1, which(diff(v) != 1) + 1, length(v) + 1) paste0(collapse=",", v[head(r, -1)], ifelse(diff(r) == 1, "", paste0(ifelse(diff(r) == 2, ",", "-"), v[r[-1] - 1]))) }     print(extract.range(c( -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20))) print(extract.range(c( 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)))
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Tosh
Tosh
when flag clicked ask "Say something..." and wait set i to (length of answer) set inv to "" repeat until i = 0 set inv to (join (inv) (letter (i) of answer)) change i by -1 end say inv
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PHP
PHP
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); }   //Alias functions public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); }   //Note: PHP prevents a method name of 'empty' public function isEmpty(){ return empty($this->data); } }
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#REXX
REXX
/*REXX program performs some operations on quaternion type numbers and displays results*/ q = 1 2 3 4  ; q1 = 2 3 4 5 r = 7  ; q2 = 3 4 5 6 call qShow q , 'q' call qShow q1 , 'q1' call qShow q2 , 'q2' call qShow r , 'r' call qShow qNorm(q) , 'norm q' , "task 1:" call qShow qNeg(q) , 'negative q' , "task 2:" call qShow qConj(q) , 'conjugate q' , "task 3:" call qShow qAdd( r, q ) , 'addition r+q' , "task 4:" call qShow qAdd(q1, q2 ) , 'addition q1+q2' , "task 5:" call qShow qMul( q, r ) , 'multiplication q*r' , "task 6:" call qShow qMul(q1, q2 ) , 'multiplication q1*q2' , "task 7:" call qShow qMul(q2, q1 ) , 'multiplication q2*q1' , "task 8:" exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ qConj: procedure; parse arg x; call qXY; return x.1 (-x.2) (-x.3) (-x.4) qNeg: procedure; parse arg x; call qXY; return -x.1 (-x.2) (-x.3) (-x.4) qNorm: procedure; parse arg x; call qXY; return sqrt(x.1**2 +x.2**2 +x.3**2 +x.4**2) qAdd: procedure; parse arg x,y; call qXY 2; return x.1+y.1 x.2+y.2 x.3+y.3 x.4+y.4 /*──────────────────────────────────────────────────────────────────────────────────────*/ qMul: procedure; parse arg x,y; call qXY y return x.1*y.1 -x.2*y.2 -x.3*y.3 -x.4*y.4 x.1*y.2 +x.2*y.1 +x.3*y.4 -x.4*y.3 , x.1*y.3 -x.2*y.4 +x.3*y.1 +x.4*y.2 x.1*y.4 +x.2*y.3 -x.3*y.2 +x.4*y.1 /*──────────────────────────────────────────────────────────────────────────────────────*/ qShow: procedure; parse arg x; call qXY; $= do m=1 for 4; _= x.m; if _==0 then iterate; if _>=0 then _= '+'_ if m\==1 then _= _ || substr('∙ijk', m, 1); $= strip($ || _, , "+") end /*m*/ say left(arg(3), 9) right(arg(2), 20) ' ──► ' $; return $ /*──────────────────────────────────────────────────────────────────────────────────────*/ qXY: do n=1 for 4; x.n= word( word(x, n) 0, 1)/1; end /*n*/ if arg()==1 then do m=1 for 4; y.m= word( word(y, m) 0, 1)/1; end /*m*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d= digits(); i=; m.=9; h=d+6 numeric digits; numeric form; if x<0 then parse value -x 'i' with x i parse value format(x, 2, 1, , 0) 'E0' with g "E" _ .; g= g *.5'e'_ % 2 do j=0 while h>9; m.j=h; h= h % 2 + 1; end /*j*/ do k=j+5 to 0 by -1; numeric digits m.k; g= (g + x/g)* .5; end /*k*/ numeric digits d; return (g/1)i /*make complex if X<0 */
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#HTML
HTML
<!DOCTYPE html> <html> <head> <title>HTML/CSS Quine</title> <style type="text/css"> * { font: 10pt monospace; }   head, style { display: block; } style { white-space: pre; }   style:before { content: "\3C""!DOCTYPE html\3E" "\A\3Chtml\3E\A" "\3Chead\3E\A" "\9\3Ctitle\3E""HTML/CSS Quine""\3C/title\3E\A" "\9\3Cstyle type=\22text/css\22\3E"; } style:after { content: "\3C/style\3E\A" "\3C/head\3E\A" "\3C""body\3E\3C/body\3E\A" "\3C/html\3E"; } </style> </head> <body></body> </html>
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Racket
Racket
  #lang racket   (define (list->ranges xs) (define (R lo hi) (if (= lo hi) (~a lo) (~a lo (if (= 1 (- hi lo)) "," "-") hi))) (let loop ([xs xs] [lo #f] [hi #f] [r '()]) (cond [(null? xs) (string-join (reverse (if lo (cons (R lo hi) r) r)) ",")] [(not hi) (loop (cdr xs) (car xs) (car xs) r)] [(= 1 (- (car xs) hi)) (loop (cdr xs) lo (car xs) r)] [else (loop xs #f #f (cons (R lo hi) r))])))   (list->ranges '(0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39)) ;; -> "0-2,4,6-8,11,12,14-25,27-33,35-39"  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Transd
Transd
#lang transd   MainModule : { _start: (lambda (with s "as⃝df̅" (textout (reverse s))   // reversing user input (textout "\nPlease, enter a string: ") (textout "Input: " (reverse (read s))) )) }
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Picat
Picat
go => println("Test 1"), queue_test1, nl.   empty(Q) => Q = []. push(Queue, Value) = Q2 => Q2 = [Value] ++ Queue. pop(Q,_) = _, Q==[] ; var(Q) => throw $error(empty_queue,pop,'Q'=Q). pop(Queue,Q2) = Queue.last() => Q2 = [Queue[I] : I in 1..Queue.len-1].   queue_test1 =>    % create an empty queue println("Start test 2"), empty(Q0), printf("Create queue %w%n%n", Q0),    % add numbers 1 and 2 println("Add numbers 1 and 2 : "), Q1 = Q0.push(1), Q2 = Q1.push(2),    % display queue printf("Q2: %w\n\n", Q2),    % pop element V = Q2.pop(Q3),    % display results printf("Pop : Value: %w Queue: %w\n\n", V, Q3),    % test the queue print("Test of the queue: "), ( Q3.empty() -> println("Queue empty"); println("Queue not empty") ), nl,    % pop the elements print("Pop the queue : "), V1 = Q3.pop(Q4), printf("Value %w Queue : %w%n%n", V1, Q4),   println("Pop empty queue:"), catch(_V = Q4.pop(_Q5),Exception,println(Exception)), nl,   println("\nEnd of tests.").
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Ruby
Ruby
class Quaternion def initialize(*parts) raise ArgumentError, "wrong number of arguments (#{parts.size} for 4)" unless parts.size == 4 raise ArgumentError, "invalid value of quaternion parts #{parts}" unless parts.all? {|x| x.is_a?(Numeric)} @parts = parts end   def to_a; @parts; end def to_s; "Quaternion#{@parts.to_s}" end alias inspect to_s def complex_parts; [Complex(*to_a[0..1]), Complex(*to_a[2..3])]; end   def real; @parts.first; end def imag; @parts[1..3]; end def conj; Quaternion.new(real, *imag.map(&:-@)); end def norm; Math.sqrt(to_a.reduce(0){|sum,e| sum + e**2}) end # In Rails: Math.sqrt(to_a.sum { e**2 })   def ==(other) case other when Quaternion; to_a == other.to_a when Numeric; to_a == [other, 0, 0, 0] else false end end def -@; Quaternion.new(*to_a.map(&:-@)); end def -(other); self + -other; end   def +(other) case other when Numeric Quaternion.new(real + other, *imag) when Quaternion Quaternion.new(*to_a.zip(other.to_a).map { |x,y| x + y }) # In Rails: zip(other).map(&:sum) end end   def *(other) case other when Numeric Quaternion.new(*to_a.map { |x| x * other }) when Quaternion # Multiplication of quaternions in C x C space. See "Cayley-Dickson construction". a, b, c, d = *complex_parts, *other.complex_parts x, y = a*c - d.conj*b, a*d + b*c.conj Quaternion.new(x.real, x.imag, y.real, y.imag) end end   # Coerce is called by Ruby to return a compatible type/receiver when the called method/operation does not accept a Quaternion def coerce(other) case other when Numeric then [Scalar.new(other), self] else raise TypeError, "#{other.class} can't be coerced into #{self.class}" end end   class Scalar def initialize(val); @val = val; end def +(other); other + @val; end def *(other); other * @val; end def -(other); Quaternion.new(@val, 0, 0, 0) - other; end end end   if __FILE__ == $0 q = Quaternion.new(1,2,3,4) q1 = Quaternion.new(2,3,4,5) q2 = Quaternion.new(3,4,5,6) r = 7 expressions = ["q", "q1", "q2", "q.norm", "-q", "q.conj", "q + r", "r + q","q1 + q2", "q2 + q1", "q * r", "r * q", "q1 * q2", "q2 * q1", "(q1 * q2 != q2 * q1)", "q - r", "r - q"] expressions.each do |exp| puts "%20s = %s" % [exp, eval(exp)] end end
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Huginn
Huginn
#! /bin/sh exec huginn --no-argv -E "${0}" #! huginn   main() { c = "#! /bin/sh{1}~" "exec huginn --no-argv -E {3}${{0}}{3}{1}#! huginn{1}{1}~" "main() {{{1}{2}c = {3}{0}{3};{1}{2}print({1}~" "{2}{2}copy( c ).replace( {3}{5}{3}, {3}{3} )~" ".format({1}{2}{2}{2}c.replace( {3}{5}{3}, ~" "{3}{5}{4}{3}{4}n{4}t{4}t{4}{3}{3} ), ~" "{3}{4}n{3}, {3}{4}t{3}, {3}{4}{3}{3}, {3}{4}{4}{3}, ~" "{3}{5}{3}{1}{2}{2}){1}{2});{1}}}{1}{1}"; print( copy( c ).replace( "~", "" ).format( c.replace( "~", "~\"\n\t\t\"" ), "\n", "\t", "\"", "\\", "~" ) ); }
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Raku
Raku
sub range-extraction (*@ints) { my $prev = NaN; my @ranges;   for @ints -> $int { if $int == $prev + 1 { @ranges[*-1].push: $int; } else { @ranges.push: [$int]; } $prev = $int; } join ',', @ranges.map: -> @r { @r > 2 ?? "@r[0]-@r[*-1]" !! @r } }   say range-extraction -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20;   say range-extraction 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39;
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Turing
Turing
function reverse (s : string) : string var rs := "" for i : 0 .. length (s) - 1 rs := rs + s (length (s) - i) end for result rs end reverse   put reverse ("iterative example") put reverse (reverse ("iterative example"))
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PicoLisp
PicoLisp
(off Queue) # Clear Queue (fifo 'Queue 1) # Store number '1' (fifo 'Queue 'abc) # an internal symbol 'abc' (fifo 'Queue "abc") # a transient symbol "abc" (fifo 'Queue '(a b c)) # and a list (a b c) Queue # Show the queue
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Rust
Rust
use std::fmt::{Display, Error, Formatter}; use std::ops::{Add, Mul, Neg};   #[derive(Clone,Copy,Debug)] struct Quaternion { a: f64, b: f64, c: f64, d: f64 }   impl Quaternion { pub fn new(a: f64, b: f64, c: f64, d: f64) -> Quaternion { Quaternion { a: a, b: b, c: c, d: d } }   pub fn norm(&self) -> f64 { (self.a.powi(2) + self.b.powi(2) + self.c.powi(2) + self.d.powi(2)).sqrt() }   pub fn conjugate(&self) -> Quaternion { Quaternion { a: self.a, b: -self.b, c: -self.c, d: -self.d } } }   impl Add for Quaternion { type Output = Quaternion;   #[inline] fn add(self, other: Quaternion) -> Self::Output { Quaternion { a: self.a + other.a, b: self.b + other.b, c: self.c + other.c, d: self.d + other.d } } }   impl Add<f64> for Quaternion { type Output = Quaternion;   #[inline] fn add(self, other: f64) -> Self::Output { Quaternion { a: self.a + other, b: self.b, c: self.c, d: self.d } } }   impl Add<Quaternion> for f64 { type Output = Quaternion;   #[inline] fn add(self, other: Quaternion) -> Self::Output { Quaternion { a: other.a + self, b: other.b, c: other.c, d: other.d } } }   impl Display for Quaternion { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { write!(f, "({} + {}i + {}j + {}k)", self.a, self.b, self.c, self.d) } }   impl Mul for Quaternion { type Output = Quaternion;   #[inline] fn mul(self, rhs: Quaternion) -> Self::Output { Quaternion { a: self.a * rhs.a - self.b * rhs.b - self.c * rhs.c - self.d * rhs.d, b: self.a * rhs.b + self.b * rhs.a + self.c * rhs.d - self.d * rhs.c, c: self.a * rhs.c - self.b * rhs.d + self.c * rhs.a + self.d * rhs.b, d: self.a * rhs.d + self.b * rhs.c - self.c * rhs.b + self.d * rhs.a, } } }   impl Mul<f64> for Quaternion { type Output = Quaternion;   #[inline] fn mul(self, other: f64) -> Self::Output { Quaternion { a: self.a * other, b: self.b * other, c: self.c * other, d: self.d * other } } }   impl Mul<Quaternion> for f64 { type Output = Quaternion;   #[inline] fn mul(self, other: Quaternion) -> Self::Output { Quaternion { a: other.a * self, b: other.b * self, c: other.c * self, d: other.d * self } } }   impl Neg for Quaternion { type Output = Quaternion;   #[inline] fn neg(self) -> Self::Output { Quaternion { a: -self.a, b: -self.b, c: -self.c, d: -self.d } } }   fn main() { let q0 = Quaternion { a: 1., b: 2., c: 3., d: 4. }; let q1 = Quaternion::new(2., 3., 4., 5.); let q2 = Quaternion::new(3., 4., 5., 6.); let r: f64 = 7.;   println!("q0 = {}", q0); println!("q1 = {}", q1); println!("q2 = {}", q2); println!("r = {}", r); println!(); println!("-q0 = {}", -q0); println!("conjugate of q0 = {}", q0.conjugate()); println!(); println!("r + q0 = {}", r + q0); println!("q0 + r = {}", q0 + r); println!(); println!("r * q0 = {}", r * q0); println!("q0 * r = {}", q0 * r); println!(); println!("q0 + q1 = {}", q0 + q1); println!("q0 * q1 = {}", q0 * q1); println!(); println!("q0 * (conjugate of q0) = {}", q0 * q0.conjugate()); println!(); println!(" q0 + q1 * q2 = {}", q0 + q1 * q2); println!("(q0 + q1) * q2 = {}", (q0 + q1) * q2); println!(); println!(" q0 * q1 * q2 = {}", q0 *q1 * q2); println!("(q0 * q1) * q2 = {}", (q0 * q1) * q2); println!(" q0 * (q1 * q2) = {}", q0 * (q1 * q2)); println!(); println!("normal of q0 = {}", q0.norm()); }
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Icon_and_Unicon
Icon and Unicon
procedure main();x:="write(\"procedure main();x:=\",image(x));write(x);end" write("procedure main();x:=",image(x));write(x);end
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#REXX
REXX
/*REXX program creates a range extraction from a list of numbers (can be negative.) */ old=0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 #= words(old) /*number of integers in the number list*/ new= /*the new list, possibly with ranges. */ do j=1 to #; z= word(old, j) /*obtain Jth number in the old list. */ inc= 1; new= new','z /*append " " to " new " */ do k=j+1 to #; y= word(old, k) /*get the Kth number in the number list*/ if y\==z+inc then leave /*is this number not > previous by inc?*/ inc= inc + 1; g= y /*increase the range, assign G (good).*/ end /*k*/ if k-1=j | g=z+1 then iterate /*Is the range=0│1? Then keep truckin'*/ new= new'-'g; j= k - 1 /*indicate a range of #s; change index*/ end /*j*/ /*stick a fork in it, we're all done. */ new= substr(new, 2) /*elide the leading comma in the range.*/ say 'old:' old; say 'new:' new /*show the old and new range of numbers*/
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT SET input="was it really a big fat cat i saw" SET reversetext=TURN (input) PRINT "before: ",input PRINT "after: ",reversetext
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PL.2FI
PL/I
  /* To push a node onto the end of the queue. */ push: procedure (tail); declare tail handle (node), t handle (node); t = new(:node:); get (t => value); if tail ^= bind(:null, node:) then tail => link = t; /* If the queue was non-empty, points the tail of the queue */ /* to the new node. */ tail = t; /* Point "tail" at the end of the queue. */ tail => link = bind(:node, null:); end push;   /* To pop a node from the head of the queue. */ pop: procedure (head, val); declare head handle (node), val fixed binary; if head = bind(:node, null:) then signal error; val = head => value; head = head => pointer; /* pops the top node. */ if head = bind(:node, null:) then tail = head; /* (If the queue is now empty, make tail null also.) */ end pop;   /* Queue status: the EMPTY function, returns true for empty queue. */ empty: procedure (h) returns (bit(1)); declare h handle (Node); return (h = bind(:Node, null:) ); end empty;  
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Scala
Scala
case class Quaternion(re: Double = 0.0, i: Double = 0.0, j: Double = 0.0, k: Double = 0.0) { lazy val im = (i, j, k) private lazy val norm2 = re*re + i*i + j*j + k*k lazy val norm = math.sqrt(norm2)   def negative = Quaternion(-re, -i, -j, -k) def conjugate = Quaternion(re, -i, -j, -k) def reciprocal = Quaternion(re/norm2, -i/norm2, -j/norm2, -k/norm2)   def +(q: Quaternion) = Quaternion(re+q.re, i+q.i, j+q.j, k+q.k) def -(q: Quaternion) = Quaternion(re-q.re, i-q.i, j-q.j, k-q.k) def *(q: Quaternion) = Quaternion( re*q.re - i*q.i - j*q.j - k*q.k, re*q.i + i*q.re + j*q.k - k*q.j, re*q.j - i*q.k + j*q.re + k*q.i, re*q.k + i*q.j - j*q.i + k*q.re ) def /(q: Quaternion) = this * q.reciprocal   def unary_- = negative def unary_~ = conjugate   override def toString = "Q(%.2f, %.2fi, %.2fj, %.2fk)".formatLocal(java.util.Locale.ENGLISH, re, i, j, k) }   object Quaternion { import scala.language.implicitConversions import Numeric.Implicits._   implicit def number2Quaternion[T:Numeric](n: T) = Quaternion(n.toDouble) }
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Inform_7
Inform 7
R is a room. To quit: (- quit; -). When play begins: say entry 1 in Q; say Q in brace notation; quit. Q is a list of text variable. Q is {"R is a room. To quit: (- quit; -). When play begins: say entry 1 in Q; say Q in brace notation; quit. Q is a list of text variable. Q is "}
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Ring
Ring
  # Project : Range extraction   int = "0,1,2,4,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,27,28,29,30,31,32,33,35,36,37,38,39" int = str2list(substr(int, ",", nl)) sumint = [] intnew = 1 for n=1 to len(int) flag = 0 nr = 0 intnew = 0 for m=n to len(int)-1 if int[m] = int[m+1] - 1 intnew = m+1 flag = 1 nr = nr + 1 else exit ok next if flag = 1 and nr > 1 if intnew != 0 add(sumint, [n,intnew]) n = m ok else add(sumint, [n,""]) ok next showarray(sumint)   func showarray(vect) see "[" svect = "" for n = 1 to len(vect) if vect[n][2] != "" svect = svect +"" + int[vect[n][1]] + "-" + int[vect[n][2]] + ", " else svect = svect +"" + int[vect[n][1]] + ", " ok next svect = left(svect, len(svect) - 2) see svect see "]" + nl  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#UNIX_Shell
UNIX Shell
  #!/bin/bash str=abcde   for((i=${#str}-1;i>=0;i--)); do rev="$rev${str:$i:1}"; done   echo $rev  
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PostScript
PostScript
  % our queue is just [] and empty? is already defined. /push {exch tadd}. /pop {uncons exch}.  
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i";     # Define the quaternion number data type. const type: quaternion is new object struct var float: a is 0.0; var float: b is 0.0; var float: c is 0.0; var float: d is 0.0; end struct;     # Create a quaternion number from its real and imaginary parts. const func quaternion: quaternion (in float: a, in float: b, in float: c, in float: d) is func result var quaternion: aQuaternion is quaternion.value; begin aQuaternion.a := a; aQuaternion.b := b; aQuaternion.c := c; aQuaternion.d := d; end func;     # Helper function for str(). const func string: signed (in float: number, in string: part) is func result var string: stri is str(number) & part; begin if number > 0.0 then stri := "+" & stri; elsif number = 0.0 then stri := ""; end if; end func;     # Convert a quaternion number to a string. const func string: str (in quaternion: number) is func result var string: stri is ""; begin if number.a <> 0.0 then stri &:= str(number.a); end if; stri &:= signed(number.b, "i"); stri &:= signed(number.c, "j"); stri &:= signed(number.d, "k"); end func;     # Compute the norm of a quaternion number. const func float: norm (in quaternion: number) is func result var float: qnorm is 0.0; begin qnorm := sqrt( number.a ** 2.0 + number.b ** 2.0 + number.c ** 2.0 + number.d ** 2.0 ); end func;     # Compute the negative of a quaternion number. const func quaternion: - (in quaternion: number) is func result var quaternion: negatedNumber is quaternion.value; begin negatedNumber.a := -number.a; negatedNumber.b := -number.b; negatedNumber.c := -number.c; negatedNumber.d := -number.d; end func;     # Compute the conjugate of a quaternion number. const func quaternion: conjugate (in quaternion: number) is func result var quaternion: conjugateNumber is quaternion.value; begin conjugateNumber.a := number.a; conjugateNumber.b := -number.b; conjugateNumber.c := -number.c; conjugateNumber.d := -number.d; end func;     # Add a float to a quaternion number. const func quaternion: (in quaternion: number) + (in float: real) is func result var quaternion: sum is quaternion.value; begin sum.a := number.a + real; sum.b := number.b; sum.c := number.c; sum.d := number.d; end func;     # Add a quaternion number to a float. const func quaternion: (in float: real) + (in quaternion: number) is return number + real;     # Add two quaternion numbers. const func quaternion: (in quaternion: number1) + (in quaternion: number2) is func result var quaternion: sum is quaternion.value; begin sum.a := number1.a + number2.a; sum.b := number1.b + number2.b; sum.c := number1.c + number2.c; sum.d := number1.d + number2.d; end func;     # Multiply a float and a quaternion number. const func quaternion: (in float: real) * (in quaternion: number) is func result var quaternion: product is quaternion.value; begin product.a := number.a * real; product.b := number.b * real; product.c := number.c * real; product.d := number.d * real; end func;     # Multiply a quaternion number and a float. const func quaternion: (in quaternion: number) * (in float: real) is return real * number;     # Multiply two quaternion numbers. const func quaternion: (in quaternion: x) * (in quaternion: y) is func result var quaternion: product is quaternion.value; begin product.a := x.a * y.a - x.b * y.b - x.c * y.c - x.d * y.d; product.b := x.a * y.b + x.b * y.a + x.c * y.d - x.d * y.c; product.c := x.a * y.c - x.b * y.d + x.c * y.a + x.d * y.b; product.d := x.a * y.d + x.b * y.c - x.c * y.b + x.d * y.a; end func;     # Allow quaternions to be written using write(), writeln() etc. enable_output(quaternion);     # Demonstrate quaternion numbers. const proc: main is func local const quaternion: q is quaternion(1.0, 2.0, 3.0, 4.0); const quaternion: q1 is quaternion(2.0, 3.0, 4.0, 5.0); const quaternion: q2 is quaternion(3.0, 4.0, 5.0, 6.0); const float: r is 7.0; begin writeln(" q = " <& q); writeln("q1 = " <& q1); writeln("q2 = " <& q2); writeln(" r = " <& r <& "\n");   writeln("norm(q) = " <& norm(q)); writeln("-q = " <& -q); writeln("conjugate(q) = " <& conjugate(q)); writeln("q + r = " <& q + r); writeln("r + q = " <& r + q); writeln("q1 + q2 = " <& q1 + q2); writeln("q2 + q1 = " <& q2 + q1); writeln("q * r = " <& q * r); writeln("r * q = " <& r * q); writeln("q1 * q2 = " <& q1 * q2); writeln("q2 * q1 = " <& q2 * q1); end func;
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#INTERCAL
INTERCAL
thisMessage print
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Ruby
Ruby
def range_extract(l) # pad the list with a big value, so that the last loop iteration will # append something to the range sorted, range = l.sort.concat([Float::MAX]), [] canidate_number = sorted.first   # enumerate over the sorted list in pairs of current number and next by index sorted.each_cons(2) do |current_number, next_number| # if there is a gap between the current element and its next by index if current_number.succ < next_number # if current element is our first or our next by index if canidate_number == current_number # put the first element or next by index into our range as a string range << canidate_number.to_s else # if current element is not the same as the first or next # add [first or next, first or next equals current add , else -, current] seperator = canidate_number.succ == current_number ? "," : "-" range << "%d%s%d" % [canidate_number, seperator, current_number] end # make the first element the next element canidate_number = next_number end end range.join(',') end   lst = [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 ]   p rng = range_extract(lst)
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Unlambda
Unlambda
``@c`d``s`|k`@c
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PowerShell
PowerShell
  $Q = New-Object System.Collections.Queue   $Q.Enqueue( 1 ) $Q.Enqueue( 2 ) $Q.Enqueue( 3 )   $Q.Dequeue() $Q.Dequeue()   $Q.Count -eq 0 $Q.Dequeue() $Q.Count -eq 0   try { $Q.Dequeue() } catch [System.InvalidOperationException] { If ( $_.Exception.Message -eq 'Queue empty.' ) { 'Caught error' } }
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Sidef
Sidef
class Quaternion(r, i, j, k) {   func qu(*r) { Quaternion(r...) }   method to_s { "#{r} + #{i}i + #{j}j + #{k}k" } method reals { [r, i, j, k] } method conj { qu(r, -i, -j, -k) } method norm { self.reals.map { _*_ }.sum.sqrt }   method ==(Quaternion b) { self.reals == b.reals }   method +(Number b) { qu(b+r, i, j, k) } method +(Quaternion b) { qu((self.reals ~Z+ b.reals)...) }   method neg { qu(self.reals.map{ .neg }...) }   method *(Number b) { qu((self.reals»*»b)...) } method *(Quaternion b) { var (r,i,j,k) = b.reals... qu(sum(self.reals ~Z* [r, -i, -j, -k]), sum(self.reals ~Z* [i, r, k, -j]), sum(self.reals ~Z* [j, -k, r, i]), sum(self.reals ~Z* [k, j, -i, r])) } }   var q = Quaternion(1, 2, 3, 4) var q1 = Quaternion(2, 3, 4, 5) var q2 = Quaternion(3, 4, 5, 6) var r = 7   say "1) q norm = #{q.norm}" say "2) -q = #{-q}" say "3) q conj = #{q.conj}" say "4) q + r = #{q + r}" say "5) q1 + q2 = #{q1 + q2}" say "6) q * r = #{q * r}" say "7) q1 * q2 = #{q1 * q2}" say "8) q1q2 #{ q1*q2 == q2*q1 ? '==' : '!=' } q2q1"
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Io
Io
thisMessage print
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Rust
Rust
use std::ops::Add;   struct RangeFinder<'a, T: 'a> { index: usize, length: usize, arr: &'a [T], }   impl<'a, T> Iterator for RangeFinder<'a, T> where T: PartialEq + Add<i8, Output=T> + Copy { type Item = (T, Option<T>); fn next(&mut self) -> Option<Self::Item> { if self.index == self.length { return None; } let lo = self.index; while self.index < self.length - 1 && self.arr[self.index + 1] == self.arr[self.index] + 1 { self.index += 1 } let hi = self.index; self.index += 1; if hi - lo > 1 { Some((self.arr[lo], Some(self.arr[hi]))) } else { if hi - lo == 1 { self.index -= 1 } Some((self.arr[lo], None)) } } }   impl<'a, T> RangeFinder<'a, T> { fn new(a: &'a [T]) -> Self { RangeFinder { index: 0, arr: a, length: a.len(), } } }   fn main() { let input_numbers : &[i8] = &[0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]; for (i, (lo, hi)) in RangeFinder::new(&input_numbers).enumerate() { if i > 0 {print!(",")} print!("{}", lo); if hi.is_some() {print!("-{}", hi.unwrap())} } println!(""); }
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ursala
Ursala
#import std   #cast %s   example = ~&x 'asdf'   verbose_example = reverse 'asdf'
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Prolog
Prolog
empty(U-V) :- unify_with_occurs_check(U, V).   push(Queue, Value, NewQueue) :- append_dl(Queue, [Value|X]-X, NewQueue).   % when queue is empty pop fails. pop([X|V]-U, X, V-U) :- \+empty([X|V]-U).   append_dl(X-Y, Y-Z, X-Z).  
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Swift
Swift
import Foundation   struct Quaternion { var a, b, c, d: Double   static let i = Quaternion(a: 0, b: 1, c: 0, d: 0) static let j = Quaternion(a: 0, b: 0, c: 1, d: 0) static let k = Quaternion(a: 0, b: 0, c: 0, d: 1) } extension Quaternion: Equatable { static func ==(lhs: Quaternion, rhs: Quaternion) -> Bool { return (lhs.a, lhs.b, lhs.c, lhs.d) == (rhs.a, rhs.b, rhs.c, rhs.d) } } extension Quaternion: ExpressibleByIntegerLiteral { init(integerLiteral: Double) { a = integerLiteral b = 0 c = 0 d = 0 } } extension Quaternion: Numeric { var magnitude: Double { return norm } init?<T>(exactly: T) { // stub to satisfy protocol requirements return nil } public static func + (lhs: Quaternion, rhs: Quaternion) -> Quaternion { return Quaternion( a: lhs.a + rhs.a, b: lhs.b + rhs.b, c: lhs.c + rhs.c, d: lhs.d + rhs.d ) } public static func - (lhs: Quaternion, rhs: Quaternion) -> Quaternion { return Quaternion( a: lhs.a - rhs.a, b: lhs.b - rhs.b, c: lhs.c - rhs.c, d: lhs.d - rhs.d ) } public static func * (lhs: Quaternion, rhs: Quaternion) -> Quaternion { return Quaternion( a: lhs.a*rhs.a - lhs.b*rhs.b - lhs.c*rhs.c - lhs.d*rhs.d, b: lhs.a*rhs.b + lhs.b*rhs.a + lhs.c*rhs.d - lhs.d*rhs.c, c: lhs.a*rhs.c - lhs.b*rhs.d + lhs.c*rhs.a + lhs.d*rhs.b, d: lhs.a*rhs.d + lhs.b*rhs.c - lhs.c*rhs.b + lhs.d*rhs.a ) } public static func += (lhs: inout Quaternion, rhs: Quaternion) { lhs = Quaternion( a: lhs.a + rhs.a, b: lhs.b + rhs.b, c: lhs.c + rhs.c, d: lhs.d + rhs.d ) } public static func -= (lhs: inout Quaternion, rhs: Quaternion) { lhs = Quaternion( a: lhs.a - rhs.a, b: lhs.b - rhs.b, c: lhs.c - rhs.c, d: lhs.d - rhs.d ) } public static func *= (lhs: inout Quaternion, rhs: Quaternion) { lhs = Quaternion( a: lhs.a*rhs.a - lhs.b*rhs.b - lhs.c*rhs.c - lhs.d*rhs.d, b: lhs.a*rhs.b + lhs.b*rhs.a + lhs.c*rhs.d - lhs.d*rhs.c, c: lhs.a*rhs.c - lhs.b*rhs.d + lhs.c*rhs.a + lhs.d*rhs.b, d: lhs.a*rhs.d + lhs.b*rhs.c - lhs.c*rhs.b + lhs.d*rhs.a ) } } extension Quaternion: CustomStringConvertible { var description: String { let formatter = NumberFormatter() formatter.positivePrefix = "+" let f: (Double) -> String = { formatter.string(from: $0 as NSNumber)! } return [f(a), f(b), "i", f(c), "j", f(d), "k"].joined() } } extension Quaternion { var norm: Double { return sqrt(a*a + b*b + c*c + d*d) } var conjugate: Quaternion { return Quaternion(a: a, b: -b, c: -c, d: -d) } public static func + (lhs: Double, rhs: Quaternion) -> Quaternion { var result = rhs result.a += lhs return result } public static func + (lhs: Quaternion, rhs: Double) -> Quaternion { var result = lhs result.a += rhs return result } public static func * (lhs: Double, rhs: Quaternion) -> Quaternion { return Quaternion(a: lhs*rhs.a, b: lhs*rhs.b, c: lhs*rhs.c, d: lhs*rhs.d) } public static func * (lhs: Quaternion, rhs: Double) -> Quaternion { return Quaternion(a: lhs.a*rhs, b: lhs.b*rhs, c: lhs.c*rhs, d: lhs.d*rhs) } public static prefix func - (x: Quaternion) -> Quaternion { return Quaternion(a: -x.a, b: -x.b, c: -x.c, d: -x.d) } }   let q: Quaternion = 1 + 2 * .i + 3 * .j + 4 * .k // 1+2i+3j+4k let q1: Quaternion = 2 + 3 * .i + 4 * .j + 5 * .k // 2+3i+4j+5k let q2: Quaternion = 3 + 4 * .i + 5 * .j + 6 * .k // 3+4i+5j+6k let r: Double = 7   print(""" q = \(q) q1 = \(q1) q2 = \(q2) r = \(r) -q = \(-q) ‖q‖ = \(q.norm) conjugate of q = \(q.conjugate) r + q = q + r = \(r+q) = \(q+r) q₁ + q₂ = \(q1 + q2) = \(q2 + q1) qr = rq = \(q*r) = \(r*q) q₁q₂ = \(q1 * q2) q₂q₁ = \(q2 * q1) q₁q₂ ≠ q₂q₁ is \(q1*q2 != q2*q1) """)
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#J
J
   
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Java
Java
(function(){print("("+arguments.callee.toString().replace(/\s/g,'')+")()");})()
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Scala
Scala
object Range { def spanRange(ls:List[Int])={ var last=ls.head ls span {x => val b=x<=last+1; last=x; b} }   def toRangeList(ls:List[Int]):List[List[Int]]=ls match { case Nil => List() case _ => spanRange(ls) match { case (range, Nil) => List(range) case (range, rest) => range :: toRangeList(rest) } }   def toRangeString(ls:List[List[Int]])=ls map {r=> if(r.size<3) r mkString "," else r.head + "-" + r.last } mkString ","   def main(args: Array[String]): Unit = { var l=List(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39) println(toRangeString(toRangeList(l))) } }
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Vala
Vala
int main (string[] args) { if (args.length < 2) { stdout.printf ("Please, input a string.\n"); return 0; } var str = new StringBuilder (); for (var i = 1; i < args.length; i++) { str.append (args[i] + " "); } stdout.printf ("%s\n", str.str.strip ().reverse ()); return 0; }
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PureBasic
PureBasic
NewList MyStack()   Procedure Push(n) Shared MyStack() LastElement(MyStack()) AddElement(MyStack()) MyStack()=n EndProcedure   Procedure Pop() Shared MyStack() Protected n If FirstElement(MyStack()) ; e.g. Stack not empty n=MyStack() DeleteElement(MyStack(),1) Else Debug "Pop(), out of range. Error at line "+str(#PB_Compiler_Line) EndIf ProcedureReturn n EndProcedure   Procedure Empty() Shared MyStack() If ListSize(MyStack())=0 ProcedureReturn #True EndIf ProcedureReturn #False EndProcedure   ;---- Example of implementation ---- Push(3) Push(1) Push(4) While Not Empty() Debug Pop() Wend ;---- Now an extra Pop(), e.g. one to many ---- Debug Pop()
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Tcl
Tcl
package require TclOO   # Support class that provides C++-like RAII lifetimes oo::class create RAII-support { constructor {} { upvar 1 { end } end lappend end [self] trace add variable end unset [namespace code {my destroy}] } destructor { catch { upvar 1 { end } end trace remove variable end unset [namespace code {my destroy}] } } method return {{level 1}} { incr level upvar 1 { end } end upvar $level { end } parent trace remove variable end unset [namespace code {my destroy}] lappend parent [self] trace add variable parent unset [namespace code {my destroy}] return -level $level [self] } }   # Class of quaternions oo::class create Q { superclass RAII-support variable R I J K constructor {{real 0} {i 0} {j 0} {k 0}} { next namespace import ::tcl::mathfunc::* ::tcl::mathop::* variable R [double $real] I [double $i] J [double $j] K [double $k] } self method return args { [my new {*}$args] return 2 }   method p {} { return "Q($R,$I,$J,$K)" } method values {} { list $R $I $J $K }   method Norm {} { + [* $R $R] [* $I $I] [* $J $J] [* $K $K] }   method conjugate {} { Q return $R [- $I] [- $J] [- $K] } method norm {} { sqrt [my Norm] } method unit {} { set n [my norm] Q return [/ $R $n] [/ $I $n] [/ $J $n] [/ $K $n] } method reciprocal {} { set n2 [my Norm] Q return [/ $R $n2] [/ $I $n2] [/ $J $n2] [/ $K $n2] } method - {{q ""}} { if {[llength [info level 0]] == 2} { Q return [- $R] [- $I] [- $J] [- $K] } [my + [$q -]] return } method + q { if {[info object isa object $q]} { lassign [$q values] real i j k Q return [+ $R $real] [+ $I $i] [+ $J $j] [+ $K $k] } Q return [+ $R [double $q]] $I $J $K } method * q { if {[info object isa object $q]} { lassign [my values] a1 b1 c1 d1 lassign [$q values] a2 b2 c2 d2 Q return [expr {$a1*$a2 - $b1*$b2 - $c1*$c2 - $d1*$d2}] \ [expr {$a1*$b2 + $b1*$a2 + $c1*$d2 - $d1*$c2}] \ [expr {$a1*$c2 - $b1*$d2 + $c1*$a2 + $d1*$b2}] \ [expr {$a1*$d2 + $b1*$c2 - $c1*$b2 + $d1*$a2}] } set f [double $q] Q return [* $R $f] [* $I $f] [* $J $f] [* $K $f] } method == q { expr { [info object isa object $q] && [info object isa typeof $q [self class]] && [my values] eq [$q values] } }   export - + * == }
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#JavaScript
JavaScript
(function(){print("("+arguments.callee.toString().replace(/\s/g,'')+")()");})()
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Scheme
Scheme
  (define (make-range start end) (cond ((= start end) `("," ,start)) ((= end (+ start 1)) `("," ,start "," ,end)) (else `("," ,start "-" ,end))))   (define (range-extract-0 start end a) (cond ((null? a) (make-range start end)) ((= (+ 1 end) (car a)) (range-extract-0 start (car a) (cdr a))) (else (append (make-range start end) (range-extract-0 (car a) (car a) (cdr a))))))   (define (range-extract a) (apply string-append (map (lambda (x) (if (number? x) (number->string x) x)) (cdr (range-extract-0 (car a) (car a) (cdr a))))))   (range-extract '( 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39))  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#VBA
VBA
Public Function Reverse(aString as String) as String ' returns the reversed string dim L as integer 'length of string dim newString as string   newString = "" L = len(aString) for i = L to 1 step -1 newString = newString & mid$(aString, i, 1) next Reverse = newString End Function
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Python
Python
class FIFO(object): def __init__(self, *args): self.contents = list(args) def __call__(self): return self.pop() def __len__(self): return len(self.contents) def pop(self): return self.contents.pop(0) def push(self, item): self.contents.append(item) def extend(self,*itemlist): self.contents += itemlist def empty(self): return bool(self.contents) def __iter__(self): return self def next(self): if self.empty(): raise StopIteration return self.pop()   if __name__ == "__main__": # Sample usage: f = FIFO() f.push(3) f.push(2) f.push(1) while not f.empty(): print f.pop(), # >>> 3 2 1 # Another simple example gives the same results: f = FIFO(3,2,1) while not f.empty(): print f(), # Another using the default "truth" value of the object # (implicitly calls on the length() of the object after # checking for a __nonzero__ method f = FIFO(3,2,1) while f: print f(), # Yet another, using more Pythonic iteration: f = FIFO(3,2,1) for i in f: print i,
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#VBA
VBA
Option Base 1 Private Function norm(q As Variant) As Double norm = Sqr(WorksheetFunction.SumSq(q)) End Function   Private Function negative(q) As Variant Dim res(4) As Double For i = 1 To 4 res(i) = -q(i) Next i negative = res End Function   Private Function conj(q As Variant) As Variant Dim res(4) As Double res(1) = q(1) For i = 2 To 4 res(i) = -q(i) Next i conj = res End Function   Private Function addr(r As Double, q As Variant) As Variant Dim res As Variant res = q res(1) = r + q(1) addr = res End Function   Private Function add(q1 As Variant, q2 As Variant) As Variant add = WorksheetFunction.MMult(Array(1, 1), Array(q1, q2)) End Function   Private Function multr(r As Double, q As Variant) As Variant multr = WorksheetFunction.MMult(r, q) End Function   Private Function mult(q1 As Variant, q2 As Variant) Dim res(4) As Double res(1) = q1(1) * q2(1) - q1(2) * q2(2) - q1(3) * q2(3) - q1(4) * q2(4) res(2) = q1(1) * q2(2) + q1(2) * q2(1) + q1(3) * q2(4) - q1(4) * q2(3) res(3) = q1(1) * q2(3) - q1(2) * q2(4) + q1(3) * q2(1) + q1(4) * q2(2) res(4) = q1(1) * q2(4) + q1(2) * q2(3) - q1(3) * q2(2) + q1(4) * q2(1) mult = res End Function   Private Sub quats(q As Variant) Debug.Print q(1); IIf(q(2) < 0, " - " & Abs(q(2)), " + " & q(2)); Debug.Print IIf(q(3) < 0, "i - " & Abs(q(3)), "i + " & q(3)); Debug.Print IIf(q(4) < 0, "j - " & Abs(q(4)), "j + " & q(4)); "k" End Sub   Public Sub quaternions() q = [{ 1, 2, 3, 4}] q1 = [{2, 3, 4, 5}] q2 = [{3, 4, 5, 6}] Dim r_ As Double r_ = 7# Debug.Print "q = ";: quats q Debug.Print "q1 = ";: quats q1 Debug.Print "q2 = ";: quats q2 Debug.Print "r = "; r_ Debug.Print "norm(q) = "; norm(q) Debug.Print "negative(q) = ";: quats negative(q) Debug.Print "conjugate(q) = ";: quats conj(q) Debug.Print "r + q = ";: quats addr(r_, q) Debug.Print "q1 + q2 = ";: quats add(q1, q2) Debug.Print "q * r = ";: quats multr(r_, q) Debug.Print "q1 * q2 = ";: quats mult(q1, q2) Debug.Print "q2 * q1 = ";: quats mult(q2, q1) End Sub
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Joy
Joy
"dup put putchars 10 putch." dup put putchars 10 putch.
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Jsish
Jsish
var code='var q=String.fromCharCode(39);puts("var code="+q+code+q+";eval(code)")';eval(code)
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: rangeExtraction (in array integer: numbers) is func result var string: rangeStri is ""; local var integer: index is 1; var integer: index2 is 1; begin while index <= length(numbers) do while index2 <= pred(length(numbers)) and numbers[succ(index2)] = succ(numbers[index2]) do incr(index2); end while; if succ(index) < index2 then rangeStri &:= "," <& numbers[index] <& "-" <& numbers[index2]; else while index <= index2 do rangeStri &:= "," <& numbers[index]; incr(index); end while; end if; incr(index2); index := index2; end while; rangeStri := rangeStri[2 ..]; end func;   const proc: main is func begin writeln(rangeExtraction([] (0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39))); end func;
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#VBScript
VBScript
  WScript.Echo StrReverse("asdf")  
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Quackery
Quackery
[ [] ] is queue ( --> [ )   [ [] = ] is empty? ( [ --> b )   [ nested join ] is push ( [ x --> [ )   [ dup empty? if [ $ "Queue unexpectedly empty." fail ] behead ] is pop ( [ --> [ x )
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#R
R
empty <- function() length(l) == 0 push <- function(x) { l <<- c(l, list(x)) print(l) invisible() } pop <- function() { if(empty()) stop("can't pop from an empty list") l[[1]] <<- NULL print(l) invisible() } l <- list() empty() # [1] TRUE push(3) # [[1]] # [1] 3 push("abc") # [[1]] # [1] 3 # [[2]] # [1] "abc" push(matrix(1:6, nrow=2)) # [[1]] # [1] 3 # [[2]] # [1] "abc" # [[3]] # [,1] [,2] [,3] # [1,] 1 3 5 # [2,] 2 4 6 empty() # [1] FALSE pop() # [[1]] # [1] 3 # [[2]] # [1] "abc" pop() # [[1]] # [1] 3 pop() # list() pop() # Error in pop() : can't pop from an empty list
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Visual_Basic_.NET
Visual Basic .NET
Option Compare Binary Option Explicit On Option Infer On Option Strict On   Structure Quaternion Implements IEquatable(Of Quaternion), IStructuralEquatable   Public ReadOnly A, B, C, D As Double   Public Sub New(a As Double, b As Double, c As Double, d As Double) Me.A = a Me.B = b Me.C = c Me.D = d End Sub   Public ReadOnly Property Norm As Double Get Return Math.Sqrt((Me.A ^ 2) + (Me.B ^ 2) + (Me.C ^ 2) + (Me.D ^ 2)) End Get End Property   Public ReadOnly Property Conjugate As Quaternion Get Return New Quaternion(Me.A, -Me.B, -Me.C, -Me.D) End Get End Property   Public Overrides Function Equals(obj As Object) As Boolean If TypeOf obj IsNot Quaternion Then Return False Return Me.Equals(DirectCast(obj, Quaternion)) End Function   Public Overloads Function Equals(other As Quaternion) As Boolean Implements IEquatable(Of Quaternion).Equals Return other = Me End Function   Public Overloads Function Equals(other As Object, comparer As IEqualityComparer) As Boolean Implements IStructuralEquatable.Equals If TypeOf other IsNot Quaternion Then Return False Dim q = DirectCast(other, Quaternion) Return comparer.Equals(Me.A, q.A) AndAlso comparer.Equals(Me.B, q.B) AndAlso comparer.Equals(Me.C, q.C) AndAlso comparer.Equals(Me.D, q.D) End Function   Public Overrides Function GetHashCode() As Integer Return HashCode.Combine(Me.A, Me.B, Me.C, Me.D) End Function   Public Overloads Function GetHashCode(comparer As IEqualityComparer) As Integer Implements IStructuralEquatable.GetHashCode Return HashCode.Combine( comparer.GetHashCode(Me.A), comparer.GetHashCode(Me.B), comparer.GetHashCode(Me.C), comparer.GetHashCode(Me.D)) End Function   Public Overrides Function ToString() As String Return $"Q({Me.A}, {Me.B}, {Me.C}, {Me.D})" End Function   #Region "Operators" Public Shared Operator =(left As Quaternion, right As Quaternion) As Boolean Return left.A = right.A AndAlso left.B = right.B AndAlso left.C = right.C AndAlso left.D = right.D End Operator   Public Shared Operator <>(left As Quaternion, right As Quaternion) As Boolean Return Not left = right End Operator   Public Shared Operator +(q1 As Quaternion, q2 As Quaternion) As Quaternion Return New Quaternion(q1.A + q2.A, q1.B + q2.B, q1.C + q2.C, q1.D + q2.D) End Operator   Public Shared Operator -(q As Quaternion) As Quaternion Return New Quaternion(-q.A, -q.B, -q.C, -q.D) End Operator   Public Shared Operator *(q1 As Quaternion, q2 As Quaternion) As Quaternion Return New Quaternion( (q1.A * q2.A) - (q1.B * q2.B) - (q1.C * q2.C) - (q1.D * q2.D), (q1.A * q2.B) + (q1.B * q2.A) + (q1.C * q2.D) - (q1.D * q2.C), (q1.A * q2.C) - (q1.B * q2.D) + (q1.C * q2.A) + (q1.D * q2.B), (q1.A * q2.D) + (q1.B * q2.C) - (q1.C * q2.B) + (q1.D * q2.A)) End Operator   Public Shared Widening Operator CType(d As Double) As Quaternion Return New Quaternion(d, 0, 0, 0) End Operator #End Region End Structure
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Julia
Julia
x="println(\"x=\$(repr(x))\\n\$x\")" println("x=$(repr(x))\n$x")
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#SNOBOL4
SNOBOL4
* # Absolute value define('abs(n)') :(abs_end) abs abs = ~(abs = lt(n,0) -n) n :(return) abs_end   define('rangext(str)d1,d2') :(rangext_end) rangext num = ('+' | '-' | '') span('0123456789') rxt1 str ',' span(' ') = ' ' :s(rxt1) rxt2 str num . d1 ' ' num . d2 = + d1 ('~,' ? *eq(abs(d2 - d1),1) '~' | ',') d2 :s(rxt2) rxt3 str ('~' | '-') num '~' = '-' :s(rxt3) rxt4 str '~' = ',' :s(rxt4) rangext = str :(return) rangext_end   * # Test and display test = '0, 1, 2, 4, 6, 7, 8, 11, 12, 14, ' + '15, 16, 17, 18, 19, 20, 21, 22, 23, 24, ' + '25, 27, 28, 29, 30, 31, 32, 33, 35, 36, ' + '37, 38, 39' output = rangext(test) end
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Vedit_macro_language
Vedit macro language
Reg_Empty(10) for (BOL; !At_EOL; Char) { Reg_Copy_Block(10, CP, CP+1, INSERT) }
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Racket
Racket
  #lang racket   (define (make-queue) (mcons #f #f)) (define (push! q x) (define new (mcons x #f)) (if (mcar q) (set-mcdr! (mcdr q) new) (set-mcar! q new)) (set-mcdr! q new)) (define (pop! q) (define old (mcar q)) (cond [(eq? old (mcdr q)) (set-mcar! q #f) (set-mcdr! q #f)] [else (set-mcar! q (mcdr old))]) (mcar old)) (define (empty? q) (not (mcar q)))   (define Q (make-queue)) (empty? Q) ; -> #t (push! Q 'x) (empty? Q) ; -> #f (for ([x 3]) (push! Q x)) (pop! Q)  ; -> 'x (list (pop! Q) (pop! Q) (pop! Q)) ; -> '(0 1 2)  
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Wren
Wren
class Quaternion { construct new(a, b, c, d ) { _a = a _b = b _c = c _d = d }   a { _a } b { _b } c { _c } d { _d }   norm { (a*a + b*b + c*c + d*d).sqrt }   - { Quaternion.new(-a, -b, -c, -d) }   conj { Quaternion.new(a, -b, -c, -d) }   + (q) { if (q is Num) return Quaternion.new(a + q, b, c, d) return Quaternion.new(a + q.a, b + q.b, c + q.c, d + q.d) }   * (q) { if (q is Num) return Quaternion.new(a * q, b * q, c * q, d * q) return Quaternion.new(a*q.a - b*q.b - c*q.c - d*q.d, a*q.b + b*q.a + c*q.d - d*q.c, a*q.c - b*q.d + c*q.a + d*q.b, a*q.d + b*q.c - c*q.b + d*q.a) }   == (q) { a == q.a && b == q.b && c == q.c && d == q.d } != (q) { !(this == q) }   toString { "(%(a), %(b), %(c), %(d))" }   static realAdd(r, q) { q + r }   static realMul(r, q) { q * r } }   var q = Quaternion.new(1, 2, 3, 4) var q1 = Quaternion.new(2, 3, 4, 5) var q2 = Quaternion.new(3, 4, 5, 6) var q3 = q1 * q2 var q4 = q2 * q1 var r = 7   System.print("q = %(q)") System.print("q1 = %(q1)") System.print("q2 = %(q2)") System.print("r = %(r)") System.print("norm(q) = %(q.norm)") System.print("-q = %(-q)") System.print("conj(q) = %(q.conj)") System.print("r + q = %(Quaternion.realAdd(r, q))") System.print("q + r = %(q + r))") System.print("q1 + q2 = %(q1 + q2)") System.print("q2 + q1 = %(q2 + q1)") System.print("rq = %(Quaternion.realMul(r, q))") System.print("qr = %(q * r)") System.print("q1q2 = %(q3)") System.print("q2q1 = %(q4)") System.print("q1q2 ≠ q2q1 = %(q3 != q4)")
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Kotlin
Kotlin
// version 1.1.2   const val F = """// version 1.1.2   const val F = %c%c%c%s%c%c%c   fun main(args: Array<String>) { System.out.printf(F, 34, 34, 34, F, 34, 34, 34) } """   fun main(args: Array<String>) { System.out.printf(F, 34, 34, 34, F, 34, 34, 34) }
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Swift
Swift
  import Darwin   func ranges(from ints:[Int]) -> [(Int, Int)] {   var range : (Int, Int)? var ranges = [(Int, Int)]() for this in ints { if let (start, end) = range { if this == end + 1 { range = (start, this) } else { ranges.append(range!) range = (this, this) } } else { range = (this, this) } } ranges.append(range!)   return ranges }   func description(from ranges:[(Int, Int)]) -> String { var desc = "" for (start, end) in ranges { desc += desc.isEmpty ? "" : "," if start == end { desc += "\(start)" } else if end == start + 1 { desc += "\(start),\(end)" } else { desc += "\(start)-\(end)" } } return desc }     let ex = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20] let longer = [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]   print(description(from: ranges(from: ex))) print(description(from: ranges(from: longer)))  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Visual_Basic
Visual Basic
Debug.Print VBA.StrReverse("Visual Basic")
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Raku
Raku
role FIFO { method enqueue ( *@values ) { # Add values to queue, returns the number of values added. self.push: @values; return @values.elems; } method dequeue ( ) { # Remove and return the first value from the queue. # Return Nil if queue is empty. return self.elems ?? self.shift !! Nil; } method is-empty ( ) { # Check to see if queue is empty. Returns Boolean value. return self.elems == 0; } }   # Example usage:   my @queue does FIFO;   say @queue.is-empty; # -> Bool::True for <A B C> -> $i { say @queue.enqueue: $i } # 1 \n 1 \n 1 say @queue.enqueue: Any; # -> 1 say @queue.enqueue: 7, 8; # -> 2 say @queue.is-empty; # -> Bool::False say @queue.dequeue; # -> A say @queue.elems; # -> 4 say @queue.dequeue; # -> B say @queue.is-empty; # -> Bool::False say @queue.enqueue('OHAI!'); # -> 1 say @queue.dequeue until @queue.is-empty; # -> C \n Any() \n [7 8] \n OHAI! say @queue.is-empty; # -> Bool::True say @queue.dequeue; # ->
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#XPL0
XPL0
proc QPrint(Q); \Display quaternion real Q; [RlOut(0, Q(0)); Text(0, " + "); RlOut(0, Q(1)); Text(0, "i + "); RlOut(0, Q(2)); Text(0, "j + "); RlOut(0, Q(3)); Text(0, "k"); CrLf(0); ]; func real QNorm(Q); \Return norm of a quaternion real Q; return sqrt( Q(0)*Q(0) + Q(1)*Q(1) + Q(2)*Q(2) + Q(3)*Q(3) );   func real QNeg(Q, R); \Return negative of a quaternion: Q:= -R real Q, R; [Q(0):= -R(0); Q(1):= -R(1); Q(2):= -R(2); Q(3):= -R(3); return Q; ]; func real QConj(Q, R); \Return conjugate of a quaternion: Q:= conj R real Q, R; [Q(0):= R(0); Q(1):= -R(1); Q(2):= -R(2); Q(3):= -R(3); return Q; ]; func real QRAdd(Q, R, Real); \Return quaternion plus real: Q:= R + Real real Q, R, Real; [Q(0):= R(0) + Real; Q(1):= R(1); Q(2):= R(2); Q(3):= R(3); return Q; ]; func real QAdd(Q, R, S); \Return quaternion sum: Q:= R + S real Q, R, S; [Q(0):= R(0) + S(0); Q(1):= R(1) + S(1); Q(2):= R(2) + S(2); Q(3):= R(3) + S(3); return Q; ]; func real QRMul(Q, R, Real); \Return quaternion times real: Q:= R + Real real Q, R, Real; [Q(0):= R(0) * Real; Q(1):= R(1) * Real; Q(2):= R(2) * Real; Q(3):= R(3) * Real; return Q; ]; func real QMul(Q, R, S); \Return quaternion product: Q:= R * S real Q, R, S; [Q(0):= R(0)*S(0) - R(1)*S(1) - R(2)*S(2) - R(3)*S(3); Q(1):= R(0)*S(1) + R(1)*S(0) + R(2)*S(3) - R(3)*S(2); Q(2):= R(0)*S(2) - R(1)*S(3) + R(2)*S(0) + R(3)*S(1); Q(3):= R(0)*S(3) + R(1)*S(2) - R(2)*S(1) + R(3)*S(0); return Q; ];   real Q, Q1, Q2, R, Q0(4),; [Q:= [1.0, 2.0, 3.0, 4.0]; Q1:= [2.0, 3.0, 4.0, 5.0]; Q2:= [3.0, 4.0, 5.0, 6.0]; R:= 7.0; Format(3, 1); Text(0, "q = "); QPrint(Q); Text(0, "q1 = "); QPrint(Q1); Text(0, "q2 = "); QPrint(Q2); Text(0, "norm(q) = "); RlOut(0, QNorm(Q)); CrLf(0); Text(0, "-q = "); QPrint(QNeg(Q0, Q)); Text(0, "conj(q) = "); QPrint(QConj(Q0, Q)); Text(0, "r + q = "); QPrint(QRAdd(Q0, Q, R)); Text(0, "q1 + q2 = "); QPrint(QAdd (Q0, Q1, Q2)); Text(0, "r * q = "); QPrint(QRMul(Q0, Q, R)); Text(0, "q1 * q2 = "); QPrint(QMul (Q0, Q1, Q2)); Text(0, "q2 * q1 = "); QPrint(QMul (Q0, Q2, Q1)); ]
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Lambdatalk
Lambdatalk
{{lambda {:x} :x} '{lambda {:x} :x}} -> {lambda {:x} :x}
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Tailspin
Tailspin
  templates extract data start <"1">, end <"1"> local templates out when <{start: <=$.end>}> do '$.start;' ! when <{end: <=$.start+1>}> do '$.start;,$.end;' ! otherwise '$.start;-$.end;' ! end out @: {start: $(1), end: $(1)}; [ $(2..last)... -> #, $@ -> out ] -> '$...;' ! when <[email protected]+1> do @.end: $; otherwise $@ -> out ! ',' ! @: {start: $, end: $}; end extract   [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39] -> extract -> !OUT::write  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Visual_Basic_.NET
Visual Basic .NET
#Const REDIRECTOUT = True   Module Program Const OUTPATH = "out.txt"   ReadOnly TestCases As String() = {"asdf", "as⃝df̅", "Les Misérables"}   ' SIMPLE VERSION Function Reverse(s As String) As String Dim t = s.ToCharArray() Array.Reverse(t) Return New String(t) End Function   ' EXTRA CREDIT VERSION Function ReverseElements(s As String) As String ' In .NET, a text element is series of code units that is displayed as one character, and so reversing the text ' elements of the string correctly handles combining character sequences and surrogate pairs. Dim elements = Globalization.StringInfo.GetTextElementEnumerator(s) Return String.Concat(AsEnumerable(elements).OfType(Of String).Reverse()) End Function   ' Wraps an IEnumerator, allowing it to be used as an IEnumerable. Iterator Function AsEnumerable(enumerator As IEnumerator) As IEnumerable Do While enumerator.MoveNext() Yield enumerator.Current Loop End Function   Sub Main() Const INDENT = " "   #If REDIRECTOUT Then Const OUTPATH = "out.txt" Using s = IO.File.Open(OUTPATH, IO.FileMode.Create), sw As New IO.StreamWriter(s) Console.SetOut(sw) #Else Try Console.OutputEncoding = Text.Encoding.ASCII Console.OutputEncoding = Text.Encoding.UTF8 Console.OutputEncoding = Text.Encoding.Unicode Catch ex As Exception Console.WriteLine("Failed to set console encoding to Unicode." & vbLf) End Try #End If For Each c In TestCases Console.WriteLine(c) Console.WriteLine(INDENT & "SIMPLE: " & Reverse(c)) Console.WriteLine(INDENT & "ELEMENTS: " & ReverseElements(c)) Console.WriteLine() Next #If REDIRECTOUT Then End Using #End If End Sub End Module
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#REBOL
REBOL
rebol [ Title: "FIFO" URL: http://rosettacode.org/wiki/FIFO ]   ; Define fifo class:   fifo: make object! [ queue: copy [] push: func [x][append queue x] pop: func [/local x][ ; Make 'x' local so it won't pollute global namespace. if empty [return none] x: first queue remove queue x] empty: does [empty? queue] ]   ; Create and populate a FIFO:   q: make fifo [] q/push 'a q/push 2 q/push USD$12.34 ; Did I mention that REBOL has 'money!' datatype? q/push [Athos Porthos Aramis] ; List elements pushed on one by one. q/push [[Huey Dewey Lewey]] ; This list is preserved as a list.   ; Dump it out, with narrative:   print rejoin ["Queue is " either q/empty [""]["not "] "empty."] while [not q/empty][print [" " q/pop]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] print ["Trying to pop an empty queue yields:" q/pop]
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#zkl
zkl
class Quat{ fcn init(real=0,i1=0,i2=0,i3=0){ var [const] vector= // Quat(r,i,j,k) or Quat( (r,i,j,k) ) (if(List.isType(real)) real else vm.arglist).apply("toFloat"); var r,i,j,k; r,i,j,k=vector; // duplicate data for ease of coding var [const] // properties: This is one way to do it norm2=vector.apply("pow",2).sum(0.0), // Norm squared abs=norm2.sqrt(), // Norm arg=(r/abs()).acos(), // Theta !!!this may be incorrect...  ; } fcn toString { String("[",vector.concat(","),"]") } var [const proxy] // properties that need calculation (or are recursive) conj =fcn{ Quat(r,-i,-j,-k) }, // Conjugate recip =fcn{ n2:=norm2; Quat(r/n2,-i/n2,-j/n2,-k/n2) },// Reciprocal pureim =fcn{ Quat(0, i, j, k) }, // Pure imagery versor =fcn{ self / abs; }, // Unit versor iversor=fcn{ pureim / pureim.abs; }, // Unit versor of imagery part  ;   fcn __opEQ(z) { r == z.r and i == z.i and j == z.j and k == z.k } fcn __opNEQ(z){ (not (self==z)) }   fcn __opNegate{ Quat(-r, -i, -j, -k) } fcn __opAdd(z){ if (Quat.isInstanceOf(z)) Quat(vector.zipWith('+,z.vector)); else Quat(r+z,i,j,k); } fcn __opSub(z){ if (Quat.isInstanceOf(z)) Quat(vector.zipWith('-,z.vector)); else Quat(r-z,vector.xplode(1)); // same as above } fcn __opMul(z){ if (Quat.isInstanceOf(z)){ Quat(r*z.r - i*z.i - j*z.j - k*z.k, r*z.i + i*z.r + j*z.k - k*z.j, r*z.j - i*z.k + j*z.r + k*z.i, r*z.k + i*z.j - j*z.i + k*z.r); } else Quat(vector.apply('*(z))); } fcn __opDiv(z){ if (Quat.isInstanceOf(z)) self*z.recip; else Quat(r/z,i/z,j/z,k/z); }   fcn pow(r){ exp(r*iversor*arg)*abs.pow(r) } // Power function fcn log{ iversor*(r / abs).acos() + abs.log() } fcn exp{ // e^q inorm:=pureim.abs; (iversor*inorm.sin() + inorm.cos()) * r.exp(); } }
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Lasso
Lasso
var(a=(:10,39,118,97,114,40,97,61,40,58,39,10,36,97,45,62,106,111,105,110,40,39,44,39,41,10,39,41,41,39,10,118,97,114,40,98,61,98,121,116,101,115,41,10,36,97,45,62,102,111,114,101,97,99,104,32,61,62,32,123,32,36,98,45,62,105,109,112,111,114,116,56,98,105,116,115,40,35,49,41,32,125,10,36,98,45,62,97,115,83,116,114,105,110,103)) 'var(a=(:' $a->join(',') '))' var(b=bytes) $a->foreach => { $b->import8bits(#1) } $b->asString
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Tcl
Tcl
proc rangeExtract list { set result [lindex $list 0] set first [set last [lindex $list 0]] foreach term [lrange $list 1 end] { if {$term == $last+1} { set last $term continue } if {$last > $first} { append result [expr {$last == $first+1 ? "," : "-"}] $last } append result "," $term set first [set last $term] } if {$last == $first+1} { append result "," $last } elseif {$last > $first} { append result "-" $last } return $result }   # Commas already removed so it is a natural Tcl list puts [rangeExtract { 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 }]