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/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Sidef
Sidef
func identity_matrix(n) { n.of { |i| n.of { |j| i == j ? 1 : 0 } } }   for n (ARGV ? ARGV.map{.to_i} : [4, 5, 6]) { say "\n#{n}:" for row (identity_matrix(n)) { say row.join(' ') } }
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Sidef
Sidef
var a = read("a: ", Number); var b = read("b: ", Number);   if (a < b) { say 'Lower'; } elsif (a == b) { say 'Equal'; } elsif (a > b) { say 'Greater'; }
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Slate
Slate
[ |:a :b |   ( a > b ) ifTrue: [ inform: 'a greater than b\n' ]. ( a < b ) ifTrue: [ inform: 'a less than b\n' ]. ( a = b ) ifTrue: [ inform: 'a is equal to b\n' ].   ] applyTo: {Integer readFrom: (query: 'Enter a: '). Integer readFrom: (query: 'Enter b: ')}.
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#Icon_and_Unicon
Icon and Unicon
  link cfunc procedure main(arglist) get(arglist[1]) end   procedure get(url) local f, host, port, path url ? { ="http://" | ="HTTP://" host := tab(upto(':/') | 0) if not (=":" & (port := integer(tab(upto('/'))))) then port := 80 if pos(0) then path := "/" else path := tab(0...
http://rosettacode.org/wiki/Hofstadter-Conway_$10,000_sequence
Hofstadter-Conway $10,000 sequence
The definition of the sequence is colloquially described as:   Starting with the list [1,1],   Take the last number in the list so far: 1, I'll call it x.   Count forward x places from the beginning of the list to find the first number to add (1)   Count backward x places from the end of the list to find the secon...
#Lua
Lua
  local fmt, write=string.format,io.write local hof=coroutine.wrap(function() local yield=coroutine.yield local a={1,1} yield(a[1], 1) yield(a[2], 2) local n=a[#a] repeat n=a[n]+a[1+#a-n] a[#a+1]=n yield(n, #a) until false end)   local mallows, mdiv=0,0 for p=1,20 do local max, div, num, last, fdiv=0,0,0,...
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Frink
Frink
  staticJava["java.lang.System","err"].println["Goodbye, World!"]  
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Genie
Genie
[indent=4] /* Hello, to Standard error, in Genie valac helloStderr.gs */   init stderr.printf("%s\n", "Goodbye, World!")
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Go
Go
package main func main() { println("Goodbye, World!") }
http://rosettacode.org/wiki/Hofstadter_Q_sequence
Hofstadter Q sequence
Hofstadter Q sequence Q ( 1 ) = Q ( 2 ) = 1 , Q ( n ) = Q ( n − Q ( n − 1 ) ) + Q ( n − Q ( n − 2 ) ) , n > 2. {\displaystyle {\begin{aligned}Q(1)&=Q(2)=1,\\Q(n)&=Q{\big (}n-Q(n-1){\big )}+Q{\big (}n-Q(n-2){\big )},\quad n>2.\end{aligned}}} It is defined like the Fibonacc...
#Factor
Factor
( scratchpad ) : next ( seq -- newseq ) dup 2 tail* over length [ swap - ] curry map [ dupd swap nth ] map 0 [ + ] reduce suffix ;   ( scratchpad ) { 1 1 } 1000 [ next ] times dup 10 head . 999 swap nth . { 1 1 2 3 3 4 5 5 6 6 } 502
http://rosettacode.org/wiki/Hofstadter_Q_sequence
Hofstadter Q sequence
Hofstadter Q sequence Q ( 1 ) = Q ( 2 ) = 1 , Q ( n ) = Q ( n − Q ( n − 1 ) ) + Q ( n − Q ( n − 2 ) ) , n > 2. {\displaystyle {\begin{aligned}Q(1)&=Q(2)=1,\\Q(n)&=Q{\big (}n-Q(n-1){\big )}+Q{\big (}n-Q(n-2){\big )},\quad n>2.\end{aligned}}} It is defined like the Fibonacc...
#Fermat
Fermat
Func Hq(n) = if n<2 then 1 else Array qq[n+1]; qq[1] := 1; qq[2] := 1; for i = 3, n do qq[i]:=qq[i-qq[i-1]]+qq[i-qq[i-2]] od; Return(qq[n]); fi; .   for i=1 to 10 do !Hq(i);!' ' od; Hq(1000)
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#Ring
Ring
  n = 12 hick = 0 decimals(8)   for i = 1 to n see "h(" + string(i) + ") = " see "" + hickersonSeries(i) + " " if nearly(hick) = 1 see "nearly integer" + nl else see "not nearly integer" + nl ok next   func hickersonSeries nr hick = fact(nr) / (2 * pow(log(2), nr+1)) return hick   func fact...
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#Ruby
Ruby
require "bigdecimal"   LN2 = BigMath::log(2,16) #Use LN2 = Math::log(2) to see the difference with floats FACTORIALS = Hash.new{|h,k| h[k] = k * h[k-1]} FACTORIALS[0] = 1   def hickerson(n) FACTORIALS[n] / (2 * LN2 ** (n+1)) end   def nearly_int?(n) int = n.round n.between?(int - 0.1, int + 0.1) end   1.upto(17)...
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#AArch64_Assembly
AArch64 Assembly
.equ STDOUT, 1 .equ SVC_WRITE, 64 .equ SVC_EXIT, 93   .text .global _start   _start: stp x29, x30, [sp, -16]! mov x0, #STDOUT ldr x1, =msg mov x2, 13 mov x8, #SVC_WRITE mov x29, sp svc #0 // write(stdout, msg, 13); ldp x29, x30, [sp], 16 mov x0, #0 mov x8, #SVC_EXIT svc #0 // exit(0);   msg: .ascii "Hello Wo...
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#FreeBASIC
FreeBASIC
' version 02-05-2016 ' compile with: fbc -s console   #Macro header Print Print " a b c s area" Print "-----------------------------------" #EndMacro   Type triangle Dim As UInteger a Dim As UInteger b Dim As UInteger c Dim As UInteger s Dim As UInteger area End Typ...
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Burlesque
Burlesque
  blsq ) {1 2 3 4}{5.+}m[ {6 7 8 9}  
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Java
Java
import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket;   public class HelloWorld{ public static void main(String[] args) throws IOException{ ServerSocket listener = new ServerSocket(8080); while(true){ Socket sock = listener.accept(); new Prin...
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#JavaScript
JavaScript
var http = require('http');   http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Goodbye, World!\n'); }).listen(8080, '127.0.0.1');
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Perl
Perl
$address = <<END; 1, High Street, $town_name, West Midlands. WM4 5HD. END
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Phix
Phix
string ts1 = """ this "string"\thing"""   string ts2 = """this "string"\thing"""   string ts3 = """ _____________this "string"\thing"""   string ts4 = ` this "string"\thing`   string ts5 = `this "string"\thing`   string ts6 = ` _____________this "string"\thing`   string ts7 = "this\n\"string\"...
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#PHP
PHP
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#PicoLisp
PicoLisp
(out "file.txt" # Write to "file.txt" (prinl "### This is before the text ###") (here "TEXT-END") (prinl "### This is after the text ###") ) "There must be some way out of here", said the joker to the thief "There's too much confusion, I can't get no relief" TEXT-END   (in "file.txt" (ec...
http://rosettacode.org/wiki/History_variables
History variables
Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are variables in a programming la...
#SenseTalk
SenseTalk
// HistoryVariable.script properties history: [], -- a list of all historical values asTextFormat:"[[the last item of my history]]" -- always display the last value end properties   to set newValue push newValue nested into my history end set   to rollback pop my history return it end rollback  
http://rosettacode.org/wiki/History_variables
History variables
Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are variables in a programming la...
#Sidef
Sidef
class HistoryVar(v) {   has history = [] has variable = v   method ≔(value) { history << variable variable = value }   method to_s { "#{variable}" }   method AUTOLOAD(_, name, *args) { variable.(name)(args...) } }   var foo = HistoryVar(0)   foo ≔ 1 foo ≔ ...
http://rosettacode.org/wiki/History_variables
History variables
Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are variables in a programming la...
#Smalltalk
Smalltalk
Object subclass:'HVar' instanceVariableNames:'values' classVariableNames:'' poolDictionaries:'' category:'example'. !   !HVar methodsFor:'accessing'!   <-- value (values ifNil:[values := OrderedCollection new]) add:value. ^ value !   value ^ values last !   undo values removeLast. ! ...
http://rosettacode.org/wiki/Hofstadter_Figure-Figure_sequences
Hofstadter Figure-Figure sequences
These two sequences of positive integers are defined as: R ( 1 ) = 1   ;   S ( 1 ) = 2 R ( n ) = R ( n − 1 ) + S ( n − 1 ) , n > 1. {\displaystyle {\begin{aligned}R(1)&=1\ ;\ S(1)=2\\R(n)&=R(n-1)+S(n-1),\quad n>1.\end{aligned}}} The sequence S ( n ) {\displaystyle S(n)} is further...
#Phix
Phix
with javascript_semantics sequence F = {1,3,7}, S = {2,4,5,6} integer fmax = 3 -- (ie F[3], ==7, already in S) forward function ffs(integer n) function ffr(integer n) integer l = length(F) while n>l do F &= F[l]+ffs(l) l += 1 end while return F[n] end function function ffs...
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Nim
Nim
# You can also just use `reversed` proc from stdlib `algorithm` module iterator reversed[T](x: openArray[T]): T = for i in countdown(x.high, x.low): yield x[i]   proc horner[T](coeffs: openArray[T], x: T): int = for c in reversed(coeffs): result = result * x + c   echo horner([-19, 7, -4, 6], 3)
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Oberon-2
Oberon-2
  MODULE HornerRule; IMPORT Out;   TYPE Coefs = POINTER TO ARRAY OF LONGINT; VAR coefs: Coefs;   PROCEDURE Eval(coefs: ARRAY OF LONGINT;size,x: LONGINT): LONGINT; VAR i,acc: LONGINT; BEGIN acc := 0; FOR i := LEN(coefs) - 1 TO 0 BY -1 DO acc := acc * x + coefs[i] END; RETURN acc END Eval;   BEGIN NEW...
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Processing
Processing
int iterations = 7; float strokeLen = 600; int angleDeg = 90; String axiom = "L"; StringDict rules = new StringDict(); String sentence = axiom; int xo, yo;   void setup() { size(700, 700); xo= 50; yo = height - 50; strokeWeight(1); noFill();   rules.set("L", "+RF-LFL-FR+"); rules.set("R", "-LF+RFR+FL-")...
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Needs["Calendar`"];DateFormat[x_]:=DateString[x,{"DayNameShort"," ","DayShort"," ","MonthName"}] Map[StringJoin[ToString[#]," Easter: ",DateFormat[EasterSunday[#]], ", Ascension: ",DateFormat[DaysPlus[EasterSunday[#],39]], ", Pentecost: ",DateFormat[DaysPlus[EasterSunday[#],49]], ", Trinity: ",DateFormat[DaysPlus[Easte...
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#Octave
Octave
lat = input("Enter latitude: "); lng = input("Enter longitude: "); ref = input("Enter legal meridian: "); slat = sind(lat); printf("sine of latitude: %.3f\n", slat); printf("diff longitude: %.3f\n\n", lng - ref); printf("Hour, sun hour angle, dial hour line angle from 6am to 6pm\n");   hras = [-6:6] .* 15.0 .- lng .+ r...
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#Prolog
Prolog
huffman :- L = 'this is an example for huffman encoding', atom_chars(L, LA), msort(LA, LS), packList(LS, PL), sort(PL, PLS), build_tree(PLS, A), coding(A, [], C), sort(C, SC), format('Symbol~t Weight~t~30|Code~n'), maplist(print_code, SC).   build_tree([[V1|R1], [V2|R2]|T], AF) :- V is V1 + V2, A = [V, ...
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Sinclair_ZX81_BASIC
Sinclair ZX81 BASIC
10 INPUT S 20 DIM M(S,S) 30 FOR I=1 TO S 40 LET M(I,I)=1 50 NEXT I 60 FOR I=1 TO S 70 SCROLL 80 FOR J=1 TO S 90 PRINT M(I,J); 100 NEXT J 110 PRINT 120 NEXT I
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Smalltalk
Smalltalk
| a b | 'a = ' display. a := (stdin nextLine asInteger). 'b = ' display. b := (stdin nextLine asInteger). ( a > b ) ifTrue: [ 'a greater than b' displayNl ]. ( a < b ) ifTrue: [ 'a less than b' displayNl ]. ( a = b ) ifTrue: [ 'a is equal to b' displayNl ].
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#SNOBOL4
SNOBOL4
* # Get user input output = 'Enter X,Y:' trim(input) break(',') . x ',' rem . y   output = lt(x,y) x ' is less than ' y :s(end) output = eq(x,y) x ' is equal to ' y :s(end) output = gt(x,y) x ' is greater than ' y end
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#J
J
require'web/gethttp' gethttp 'http://www.rosettacode.org'  
http://rosettacode.org/wiki/Hofstadter-Conway_$10,000_sequence
Hofstadter-Conway $10,000 sequence
The definition of the sequence is colloquially described as:   Starting with the list [1,1],   Take the last number in the list so far: 1, I'll call it x.   Count forward x places from the beginning of the list to find the first number to add (1)   Count backward x places from the end of the list to find the secon...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
a[1] := 1; a[2] := 1; a[n_] := a[n] = a[a[n-1]] + a[n-a[n-1]]   Map[Print["Max value: ",Max[Table[a[n]/n//N,{n,2^#,2^(#+1)}]]," for n between 2^",#," and 2^",(#+1)]& , Range[19]] n=2^20; While[(a[n]/n//N)<0.55,n--]; Print["Mallows number: ",n]
http://rosettacode.org/wiki/Hofstadter-Conway_$10,000_sequence
Hofstadter-Conway $10,000 sequence
The definition of the sequence is colloquially described as:   Starting with the list [1,1],   Take the last number in the list so far: 1, I'll call it x.   Count forward x places from the beginning of the list to find the first number to add (1)   Count backward x places from the end of the list to find the secon...
#MATLAB_.2F_Octave
MATLAB / Octave
function Q = HCsequence(N) Q = zeros(1,N); Q(1:2) = 1; for n = 3:N, Q(n) = Q(Q(n-1))+Q(n-Q(n-1)); end; end;
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Groovy
Groovy
System.err.println("Goodbye, World!")
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Haskell
Haskell
import System.IO main = hPutStrLn stderr "Goodbye, World!"
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Huginn
Huginn
#! /bin/sh exec huginn --no-argv -E "${0}" "${@}" #! huginn   import OperatingSystem as os;   main() { os.stderr().write( "Goodbye, World!\n" ); return ( 0 ); }
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Icon_and_Unicon
Icon and Unicon
procedure main() write(&errout, "Goodbye World" ) end
http://rosettacode.org/wiki/Hofstadter_Q_sequence
Hofstadter Q sequence
Hofstadter Q sequence Q ( 1 ) = Q ( 2 ) = 1 , Q ( n ) = Q ( n − Q ( n − 1 ) ) + Q ( n − Q ( n − 2 ) ) , n > 2. {\displaystyle {\begin{aligned}Q(1)&=Q(2)=1,\\Q(n)&=Q{\big (}n-Q(n-1){\big )}+Q{\big (}n-Q(n-2){\big )},\quad n>2.\end{aligned}}} It is defined like the Fibonacc...
#Forth
Forth
100000 constant N   : q ( n -- addr ) cells here + ;   : qinit 1 0 q ! 1 1 q ! N 2 do i i 1- q @ - q @ i i 2 - q @ - q @ + i q ! loop ;   : flips ." flips: " 0 N 1 do i q @ i 1- q @ < if 1+ then loop . cr ;   : qprint ( n -- ) 0 do i q @ . loop cr ;   qinit 10 qprint 999 q @ . cr flips b...
http://rosettacode.org/wiki/Hofstadter_Q_sequence
Hofstadter Q sequence
Hofstadter Q sequence Q ( 1 ) = Q ( 2 ) = 1 , Q ( n ) = Q ( n − Q ( n − 1 ) ) + Q ( n − Q ( n − 2 ) ) , n > 2. {\displaystyle {\begin{aligned}Q(1)&=Q(2)=1,\\Q(n)&=Q{\big (}n-Q(n-1){\big )}+Q{\big (}n-Q(n-2){\big )},\quad n>2.\end{aligned}}} It is defined like the Fibonacc...
#Fortran
Fortran
  Calculate the Hofstadter Q-sequence, using a big array rather than recursion. INTEGER ENUFF PARAMETER (ENUFF = 100000) INTEGER Q(ENUFF) !Lots of memory these days.   Q(1) = 1 !Initial values as per the definition. Q(2) = 1 Q(3:) = -123456789!This will surely cause trouble! D...
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#Rust
Rust
  use decimal::d128; use factorial::Factorial;   fn hickerson(n: u64) -> d128 { d128::from(n.factorial()) / (d128!(2) * (d128!(2).ln().pow(d128::from(n + 1)))) }   // Some details on floating-points numbers can be found at https://cheats.rs/#basic-types fn main() { for i in 1..18 { let h = hickerson(i);...
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#Scala
Scala
import scala.annotation.tailrec   object Hickerson extends App {   def almostInteger(n: Int): Boolean = { def ln2 = BigDecimal("0.69314718055994530941723212145818")   def div: BigDecimal = ln2.pow(n + 1) * 2   def factorial(num: Int): Long = { @tailrec def accumulated(acc: Long, n: Long): Long...
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#ABAP
ABAP
REPORT zgoodbyeworld. WRITE 'Hello world!'.
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#FutureBasic
FutureBasic
  include "ConsoleWindow"   // Set width of tabs def tab 10   local fn gcd( a as long, b as long ) dim as long result   if ( b != 0 ) result = fn gcd( b, a mod b) else result = abs(a) end if end fn = result   begin globals dim as long triangleInfo( 600, 4 ) end globals   local fn CalculateHeronianTriangles( numbe...
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#Go
Go
package main   import ( "fmt" "math" "sort" )   const ( n = 200 header = "\nSides P A" )   func gcd(a, b int) int { leftover := 1 var dividend, divisor int if (a > b) { dividend, divisor = a, b } else { dividend, divisor = b, a }   for (leftover != 0) { leftover = ...
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#C
C
void myFuncSimple( void (*funcParameter)(void) ) { /* ... */   (*funcParameter)(); /* Call the passed function. */ funcParameter(); /* Same as above with slight different syntax. */   /* ... */ }
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Jsish
Jsish
prompt$ jsish # require('Jsi_Websrv'); 1.01 # Jsi_Websrv('', {server:true, port:8080, pageStr:'Goodbye, World!'}); ...other terminal... prompt$ curl http://localhost:8080/page Goodbye, World!prompt$ curl http://localhost:8080/page Goodbye, World!
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Julia
Julia
using HttpServer server = Server() do req, res "Goodbye, World!" end run(server, 8080)  
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#PowerShell
PowerShell
  $XMLdata=@" <?xml version="1.0" encoding="utf-8"?> <unattend xmlns="urn:schemas-microsoft-com:unattend"> <servicing> <package action="configure"> <assemblyIdentity name="Microsoft-Windows-Foundation-Package" version="${strFullVersion}" processorArchitecture="amd64" publicKeyToken="31bf3856ad36...
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Python
Python
print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Racket
Racket
  #lang racket/base   (displayln #<<EOF Blah blah blah with indentation intact and "free" \punctuations\ EOF )  
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Raku
Raku
my $color = 'green'; say qq :to 'END'; some line color: $color another line END
http://rosettacode.org/wiki/History_variables
History variables
Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are variables in a programming la...
#Swift
Swift
var historyOfHistory = [Int]() var history:Int = 0 { willSet { historyOfHistory.append(history) } }   history = 2 history = 3 history = 4 println(historyOfHistory)  
http://rosettacode.org/wiki/History_variables
History variables
Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are variables in a programming la...
#Tcl
Tcl
# Define the history machinery proc histvar {varName operation} { upvar 1 $varName v ___history($varName) history switch -- $operation { start { set history {} if {[info exist v]} { lappend history $v } trace add variable v write [list histvar.write $varName] trace add variable v rea...
http://rosettacode.org/wiki/Hofstadter_Figure-Figure_sequences
Hofstadter Figure-Figure sequences
These two sequences of positive integers are defined as: R ( 1 ) = 1   ;   S ( 1 ) = 2 R ( n ) = R ( n − 1 ) + S ( n − 1 ) , n > 1. {\displaystyle {\begin{aligned}R(1)&=1\ ;\ S(1)=2\\R(n)&=R(n-1)+S(n-1),\quad n>1.\end{aligned}}} The sequence S ( n ) {\displaystyle S(n)} is further...
#PicoLisp
PicoLisp
(setq *RNext 2)   (de ffr (N) (cache '(NIL) N (if (= 1 N) 1 (+ (ffr (dec N)) (ffs (dec N))) ) ) )   (de ffs (N) (cache '(NIL) N (if (= 1 N) 2 (let S (inc (ffs (dec N))) (when (= S (ffr *RNext)) (inc 'S) (inc '*RNext) ) ...
http://rosettacode.org/wiki/Hofstadter_Figure-Figure_sequences
Hofstadter Figure-Figure sequences
These two sequences of positive integers are defined as: R ( 1 ) = 1   ;   S ( 1 ) = 2 R ( n ) = R ( n − 1 ) + S ( n − 1 ) , n > 1. {\displaystyle {\begin{aligned}R(1)&=1\ ;\ S(1)=2\\R(n)&=R(n-1)+S(n-1),\quad n>1.\end{aligned}}} The sequence S ( n ) {\displaystyle S(n)} is further...
#PL.2FI
PL/I
ffr: procedure (n) returns (fixed binary(31)); declare n fixed binary (31); declare v(2*n+1) bit(1); declare (i, j) fixed binary (31); declare (r, s) fixed binary (31);   v = '0'b; v(1) = '1'b;   if n = 1 then return (1);   r = 1; do i = 2 to n; do j = 2 to 2*n; if v(j) = '0'b ...
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Objeck
Objeck
  class Horner { function : Main(args : String[]) ~ Nil { coeffs := Collection.FloatVector->New(); coeffs->AddBack(-19.0); coeffs->AddBack(7.0); coeffs->AddBack(-4.0); coeffs->AddBack(6.0); PolyEval(coeffs, 3)->PrintLine(); }   function : PolyEval(coefficients : Collection.FloatVector , ...
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   typedef double (^mfunc)(double, double);   @interface NSArray (HornerRule) - (double)horner: (double)x; - (NSArray *)reversedArray; - (double)injectDouble: (double)s with: (mfunc)op; @end   @implementation NSArray (HornerRule) - (NSArray *)reversedArray { return [[self reverseObjec...
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Python
Python
'''Hilbert curve'''   from itertools import (chain, islice)     # hilbertCurve :: Int -> SVG String def hilbertCurve(n): '''An SVG string representing a Hilbert curve of degree n. ''' w = 1024 return svgFromPoints(w)( hilbertPoints(w)( hilbertTree(n) ) )     # hilb...
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#Maxima
Maxima
/* Easter sunday. Result is a list [month, day]   See: Jean Meeus, "Astronomical Formulae for Calculators", 4th edition, Willmann-Bell, 1988, p.31 */   easter_sunday(year):=block([a,b,c,d,e,f,g,h,i,k,l,m,n,p], a:remainder(year,19),[b,c]:divide(year,100),[d,e]:divide(b,4), f:quotient(b+8,25),g:quotient(b-f+1,3),h:remain...
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#OoRexx
OoRexx
/*REXX pgm shows: hour, sun hour angle, dial hour line angle, 6am ---> 6pm*/ /* Use trigonometric functions provided by rxCalc */ parse arg lat lng mer . /*get the optional arguments from the CL*/ /*None specified? Then use the default of Jules ...
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#PureBasic
PureBasic
  OpenConsole()   SampleString.s="this is an example for huffman encoding" datalen=Len(SampleString)   Structure ztree linked.c ischar.c char.c number.l left.l right.l EndStructure   Dim memc.c(datalen) CopyMemory(@SampleString, @memc(0), datalen * SizeOf(Character))   Dim tree.ztree(255)   For i=0 To datal...
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Smalltalk
Smalltalk
(Array2D identity: (UIManager default request: 'Enter size of the matrix:') asInteger) asString
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#SNUSP
SNUSP
++++>++++ a b !/?\<?\# a=b > - \# a>b - < a<b #\?/
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Sparkling
Sparkling
let a = 13, b = 37; if a < b { print("a < b"); } else if a > b { print("a > b"); } else if a == b { print("a == b"); } else { print("either a or b or both are NaN"); }
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#Java
Java
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.Charset;   public class Main { public static void main(String[] args) { var request = HttpRequest.newBuilder(URI.create("https://www.rosettacode.org")) ...
http://rosettacode.org/wiki/Hofstadter-Conway_$10,000_sequence
Hofstadter-Conway $10,000 sequence
The definition of the sequence is colloquially described as:   Starting with the list [1,1],   Take the last number in the list so far: 1, I'll call it x.   Count forward x places from the beginning of the list to find the first number to add (1)   Count backward x places from the end of the list to find the secon...
#Nim
Nim
import strutils   const last = 1 shl 20   var aList: array[last + 1, int] aList[0..2] = [-50_000, 1, 1] var v = aList[2] k1 = 2 lg2 = 1 aMax = 0.0   for n in 3..last: v = aList[v] + aList[n-v] aList[n] = v aMax = max(aMax, v.float / n.float) if (k1 and n) == 0: echo "Maximum between 2^$# and 2...
http://rosettacode.org/wiki/Hofstadter-Conway_$10,000_sequence
Hofstadter-Conway $10,000 sequence
The definition of the sequence is colloquially described as:   Starting with the list [1,1],   Take the last number in the list so far: 1, I'll call it x.   Count forward x places from the beginning of the list to find the first number to add (1)   Count backward x places from the end of the list to find the secon...
#Objeck
Objeck
bundle Default { class HofCon { function : Main(args : String[]) ~ Nil { DoSqnc(1<<20); }   function : native : DoSqnc(m : Int) ~ Nil { a_list := Int->New[m + 1]; max_df := 0; p2_max := 2; k1 := 2; lg2 := 1; amax := 0.0;   a_list[0] := 1; a_list[1] :...
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#J
J
stderr =: 1!:2&4 stderr 'Goodbye, World!'
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Java
Java
public class Err{ public static void main(String[] args){ System.err.println("Goodbye, World!"); } }
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#JavaScript
JavaScript
WScript.StdErr.WriteLine("Goodbye, World!");
http://rosettacode.org/wiki/Hofstadter_Q_sequence
Hofstadter Q sequence
Hofstadter Q sequence Q ( 1 ) = Q ( 2 ) = 1 , Q ( n ) = Q ( n − Q ( n − 1 ) ) + Q ( n − Q ( n − 2 ) ) , n > 2. {\displaystyle {\begin{aligned}Q(1)&=Q(2)=1,\\Q(n)&=Q{\big (}n-Q(n-1){\big )}+Q{\big (}n-Q(n-2){\big )},\quad n>2.\end{aligned}}} It is defined like the Fibonacc...
#FreeBASIC
FreeBASIC
  Const limite = 100000   Dim As Long Q(limite), i, cont = 0   Q(1) = 1 Q(2) = 1 For i = 3 To limite Q(i) = Q(i-Q(i-1)) + Q(i-Q(i-2)) If Q(i) < Q(i-1) Then cont += 1 Next i   Print "Primeros 10 terminos: "; For i = 1 To 10 Print Q(i) &" "; Next i Print   Print "Termino numero 1000: "; Q(1000)   Print "Ter...
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigrat.s7i";   const proc: main is func local const bigRational: ln2 is 6931471805599453094172_ / 10000000000000000000000_; var bigRational: h is 1_ / 2_ / ln2; var integer: n is 0; var string: stri is ""; begin for n range 1 to 17 do h := h * bigRation...
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#Sidef
Sidef
func h(n) { n! / (2 * pow(2.log, n+1)) }   { |n| "h(%2d) = %22s is%s almost an integer.\n".printf( n, var hn = h(n).round(-3), hn.to_s ~~ /\.[09]/ ? '' : ' NOT') } << 1..17
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#ACL2
ACL2
(cw "Hello world!~%")
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#Haskell
Haskell
import qualified Data.List as L import Data.Maybe import Data.Ord import Text.Printf   -- Determine if a number n is a perfect square and return its square root if so. -- This is used instead of sqrt to avoid fixed sized floating point numbers. perfectSqrt :: Integral a => a -> Maybe a perfectSqrt n | n == 1 = Jus...
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#C.23
C#
f=Add, f(6, 2) = 8 f=Mul, f(6, 2) = 12 f=Div, f(6, 2) = 3
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Kotlin
Kotlin
import java.io.PrintWriter import java.net.ServerSocket   fun main(args: Array<String>) { val listener = ServerSocket(8080) while(true) { val sock = listener.accept() PrintWriter(sock.outputStream, true).println("Goodbye, World!") sock.close() } }
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Lasso
Lasso
local(server) = net_tcp handle => { #server->close } #server->bind(8080) & listen & forEachAccept => { local(con) = #1   split_thread => { handle => { #con->close } local(request) = '' // Read in the request in chunks until you have it all { #request->append(#con->readSomeBytes(80...
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Raven
Raven
'Buffy the Vampire Slayer' as sender 'Spike' as recipient   [ "Dear %(recipient)s, " "I wish you to leave Sunnydale and never return. " "Not Quite Love, "%(sender)s ] "\n" join print  
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#REXX
REXX
/*REXX program demonstrates a method to use "here" documents in REXX. */ parse arg doc . /*"here" name is case sensitive. */   do j=1 for sourceline() if sourceline(j)\=='◄◄'doc then iterate do !=j+1 to sourceline() while sourceline(!)\=='◄◄.' say sourceline(...
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Ring
Ring
  text =" <<'FOO' Now is the time for all good mem to come to the aid of their country." see text + nl  
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Ruby
Ruby
address = <<END 1, High Street, #{town_name}, West Midlands. WM4 5HD. END
http://rosettacode.org/wiki/History_variables
History variables
Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are variables in a programming la...
#Wren
Wren
class HistoryVariable { construct new(initValue) { _history = [initValue] }   currentValue { _history[-1] } currentValue=(newValue) { _history.add(newValue) }   showHistory() { System.print("The variable's history, oldest values first, is:") for (item in _history) System.prin...
http://rosettacode.org/wiki/History_variables
History variables
Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are variables in a programming la...
#zkl
zkl
class HistoryVar{ var [private] _v, _history=List(), maxSz; fcn init(v,maxEntries=3){ maxSz=maxEntries; set(v) } fcn set(v){ _v=v; _history.append(T(Time.Clock.time,v)); if(_history.len()>maxSz) _history.del(0); self } fcn get(n=0){ // look back into history z:=_history.len(); ...
http://rosettacode.org/wiki/Hofstadter_Figure-Figure_sequences
Hofstadter Figure-Figure sequences
These two sequences of positive integers are defined as: R ( 1 ) = 1   ;   S ( 1 ) = 2 R ( n ) = R ( n − 1 ) + S ( n − 1 ) , n > 1. {\displaystyle {\begin{aligned}R(1)&=1\ ;\ S(1)=2\\R(n)&=R(n-1)+S(n-1),\quad n>1.\end{aligned}}} The sequence S ( n ) {\displaystyle S(n)} is further...
#Prolog
Prolog
:- use_module(library(chr)).   :- chr_constraint ffr/2, ffs/2, hofstadter/1,hofstadter/2. :- chr_option(debug, off). :- chr_option(optimize, full).   % to remove duplicates ffr(N, R1) \ ffr(N, R2) <=> R1 = R2 | true. ffs(N, R1) \ ffs(N, R2) <=> R1 = R2 | true.   % compute ffr ffr(N, R), ffr(N1, R1), ffs(N1,S1) ==> ...
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#OCaml
OCaml
# let horner coeffs x = List.fold_left (fun acc coef -> acc * x + coef) 0 (List.rev coeffs) ;; val horner : int list -> int -> int = <fun>   # let coeffs = [-19; 7; -4; 6] in horner coeffs 3 ;; - : int = 128
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Octave
Octave
function r = horner(a, x) r = 0.0; for i = length(a):-1:1 r = r*x + a(i); endfor endfunction   horner([-19, 7, -4, 6], 3)
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#QB64
QB64
_Title "Hilbert Curve" Dim Shared As Integer sw, sh, wide, cell   wide = 128: cell = 4 sw = wide * cell + cell sh = sw   Screen _NewImage(sw, sh, 8) Cls , 15: Color 0 PSet (wide * cell, wide * cell)   Call Hilbert(0, 0, wide, 0, 0)   Sleep System   Sub Hilbert (x As Integer, y As Integer, lg As Integer, p As Integer, q...
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Quackery
Quackery
[ $ "turtleduck.qky" loadfile ] now!   [ stack ] is switch.arg ( --> [ )   [ switch.arg put ] is switch ( x --> )   [ switch.arg release ] is otherwise ( --> )   [ switch.arg share  != iff ]else[ done otherwise ]'[ do ]done[ ] is case ( ...
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#.D0.9C.D0.9A-61.2F52
МК-61/52
П2 1 9 ПП 86 П3 ИП2 4 ПП 86 П4 ИП2 7 ПП 86 П5 1 9 ИП3 * 1 5 + 3 0 ПП 86 П6 2 ИП4 * 4 ИП5 * + 6 ИП6 * + 6 + 7 ПП 86 ИП6 + П1 3 П4 ИП2 1 - 2 10^x / [x] ^ ^ 4 / [x] - 2 0 + ИП1 + П3 3 1 - x>=0 76 П3 КИП4 ИП3 3 0 - x>=0 83 П3 КИП4 ИП3 ИП4 С/П П0 <-> П1 <-> / [x] ИП0 * ИП1 - /-/ В/О
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#Pascal
Pascal
Program SunDial;   Const pi = 3.14159265358979323846; dr = pi/180.0; rd = 180.0/pi; tab = chr(9);   Var lat, slat, lng, ref : Real; hla, hra : Real; h : Integer;   function tan(val : Real) : Real; begin tan := sin(val)/cos(val) end;   Begin Write('Enter latitude: '); Read(l...
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#Python
Python
from heapq import heappush, heappop, heapify from collections import defaultdict   def encode(symb2freq): """Huffman encode the given dict mapping symbols to weights""" heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()] heapify(heap) while len(heap) > 1: lo = heappop(heap) hi = he...
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Sparkling
Sparkling
function unitMatrix(n) { return map(range(n), function(k1, v1) { return map(range(n), function(k2, v2) { return v2 == v1 ? 1 : 0; }); }); }
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#SQL
SQL
  DROP TABLE test;   CREATE TABLE test(a INTEGER, b INTEGER);   INSERT INTO test VALUES (1,2);   INSERT INTO test VALUES (2,2);   INSERT INTO test VALUES (2,1);   SELECT to_char(a)||' is less than '||to_char(b) less_than FROM test WHERE a < b;   SELECT to_char(a)||' is equal to '||to_char(b) equal_to FROM test WHERE a ...
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#JavaScript
JavaScript
var req = new XMLHttpRequest(); req.onload = function() { console.log(this.responseText); };   req.open('get', 'http://rosettacode.org', true); req.send()
http://rosettacode.org/wiki/Hofstadter-Conway_$10,000_sequence
Hofstadter-Conway $10,000 sequence
The definition of the sequence is colloquially described as:   Starting with the list [1,1],   Take the last number in the list so far: 1, I'll call it x.   Count forward x places from the beginning of the list to find the first number to add (1)   Count backward x places from the end of the list to find the secon...
#Oforth
Oforth
: hofstadter(n) | l i | ListBuffer newSize(n) dup add(1) dup add(1) ->l n 2 - loop: i [ l at(l last) l at(l size l last - 1+ ) + l add ] l dup freeze ;   : hofTask | h m i | 2 20 pow ->m hofstadter(m) m seq zipWith(#[ tuck asFloat / swap Pair new ]) ->h   19 loop: i [ i . "^2 ==>" . h ext...