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/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Phix
Phix
-- -- demo\rosetta\animate_pendulum.exw -- ================================= -- -- Author Pete Lomax, March 2017 -- -- Port of animate_pendulum.exw from arwen to pGUI, which is now -- preserved as a comment below (in the distro version only). -- -- With help from lesterb, updates now in timer_cb not redraw_cb, -- vari...
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#Factor
Factor
USING: backtrack continuations kernel prettyprint sequences ; IN: amb   CONSTANT: words { { "the" "that" "a" } { "frog" "elephant" "thing" } { "walked" "treaded" "grows" } { "slowly" "quickly" } }   : letters-match? ( str1 str2 -- ? ) [ last ] [ first ] bi* = ;   : sentence-match? ( seq -- ? ) dup rest...
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#smart_BASIC
smart BASIC
PRINT "Current directory: ";CURRENT_DIR$() PRINT PRINT "Folders:" PRINT DIR "/" LIST DIRS a$,c FOR n = 0 TO c-1 PRINT ,a$(n) NEXT n PRINT PRINT "Files:" PRINT DIR "/" LIST FILES a$,c FOR n = 0 TO c-1 PRINT ,a$(n) NEXT n
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Tcl
Tcl
package require ldap set conn [ldap::connect $host $port] ldap::bind $conn $user $password
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#VBScript
VBScript
Set objConn = CreateObject("ADODB.Connection") Set objCmd = CreateObject("ADODB.Command") objConn.Provider = "ADsDSOObject" objConn.Open
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Wren
Wren
/* active_directory_connect.wren */   foreign class LDAP { construct init(host, port) {}   foreign simpleBindS(name, password)   foreign unbind() }   class C { foreign static getInput(maxSize) }   var name = "" while (name == "") { System.write("Enter name : ") name = C.getInput(40) }   var pass...
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#ActionScript
ActionScript
//Throw an error if a non-number argument is used. (typeof evaluates to // "number" for both integers and reals) function checkType(obj:Object):void { if(typeof obj != "number") throw new ArgumentError("Expected integer or float argument. Recieved " + typeof obj); } function accumulator(sum:Object):Function { ...
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Ada
Ada
with Accumulator; with Ada.Text_IO; use Ada.Text_IO;   procedure Example is package A is new Accumulator; package B is new Accumulator; begin Put_Line (Integer'Image (A.The_Function (5))); Put_Line (Integer'Image (B.The_Function (3))); Put_Line (Float'Image (A.The_Function (2.3))); end;
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#ABAP
ABAP
report z_align no standard page header. start-of-selection.   data: lt_strings type standard table of string, lv_strings type string. append: 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$' to lt_strings, 'are$delineated$by$a$single$''dollar''$character,$write$a$program' to lt_strings, ...
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#Clojure
Clojure
(ns active-object (:import (java.util Timer TimerTask)))   (defn input [integrator k] (send integrator assoc :k k))   (defn output [integrator] (:s @integrator))   (defn tick [integrator t1] (send integrator (fn [{:keys [k s t0] :as m}] (assoc m :s (+ s (/ (* (+ (k t1) (k t0)) (- t1 t0)) 2.0))...
http://rosettacode.org/wiki/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An Achilles number is a number that is powerful but imperfect. Na...
#FreeBASIC
FreeBASIC
Function GCD(n As Uinteger, d As Uinteger) As Uinteger Return Iif(d = 0, n, GCD(d, n Mod d)) End Function   Function Totient(n As Integer) As Integer Dim As Integer m, tot = 0 For m = 1 To n If GCD(m, n) = 1 Then tot += 1 Next m Return tot End Function   Function isPowerful(m As Integer) As ...
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#Factor
Factor
USING: combinators combinators.short-circuit formatting kernel literals locals math math.functions math.primes.factors math.ranges namespaces pair-rocket sequences sets ; FROM: namespaces => set ; IN: rosetta-code.aliquot   SYMBOL: terms CONSTANT: 2^47 $[ 2 47 ^ ] CONSTANT: test-cases { 11 12 28 496 220 1184 12496 ...
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Lingo
Lingo
obj = script("MyClass").new()   put obj.foo -- "FOO"   -- add new property 'bar' obj.setProp(#bar, "BAR") put obj.bar -- "BAR"
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Logtalk
Logtalk
  % we start by defining an empty object :- object(foo).   % ensure that complementing categories are allowed :- set_logtalk_flag(complements, allow).   :- end_object.   % define a complementing category, adding a new predicate :- category(bar, complements(foo)).   :- public(bar/1). bar(1). bar(2). bar(3)....
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#LOLCODE
LOLCODE
HAI 1.3   I HAS A object ITZ A BUKKIT I HAS A name, I HAS A value   IM IN YR interface VISIBLE "R U WANTIN 2 (A)DD A VAR OR (P)RINT 1? "! I HAS A option, GIMMEH option   option, WTF? OMG "A" VISIBLE "NAME: "!, GIMMEH name VISIBLE "VALUE: "!, GIMMEH value object HAS A SRS name ITZ...
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#Nanoquery
Nanoquery
import native   a = 5   println format("0x%08x", native.address(a))
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#NewLISP
NewLISP
  (set 'a '(1 2 3)) (address a)  
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#Nim
Nim
var x = 12 var xptr = addr(x) # Get address of variable echo cast[int](xptr) # and print it xptr = cast[ptr int](0xFFFE) # Set the address
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Common_Lisp
Common Lisp
(defun coefficients (p) (cond ((= p 0) #(1))   (t (loop for i from 1 upto p for result = #(1 -1) then (map 'vector #'- (concatenate 'vector result #(0)) (concatenate...
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#Erlang
Erlang
  main(_) -> AddPrimes = [N || N <- lists:seq(2,500), isprime(N) andalso isprime(digitsum(N))], io:format("The additive primes up to 500 are:~n~p~n~n", [AddPrimes]), io:format("There are ~b of them.~n", [length(AddPrimes)]).   isprime(N) when N < 2 -> false; isprime(N) -> isprime(N, 2, 0, <<1, 2, 2, 4, 2, 4...
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#Rascal
Rascal
  // Literal rascal>123 := 123 bool: true   // VariableDeclaration rascal>if(str S := "abc") >>>>>>> println("Match succeeds, S == \"<S>\""); Match succeeds, S == "abc" ok   // MultiVariable rascal>if([10, N*, 50] := [10, 20, 30, 40, 50]) >>>>>>> println("Match succeeds, N == <N>"); Match succeeds, N == [20,30,40] ...
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#REXX
REXX
/*REXX pgm builds a red/black tree (with verification & validation), balanced as needed.*/ parse arg nodes '/' insert /*obtain optional arguments from the CL*/ if nodes='' then nodes = 13.8.17 8.1.11 17.15.25 1.6 25.22.27 /*default nodes. */ if insert='' then insert= 22.44 44.66 ...
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Groovy
Groovy
  public class almostprime { public static boolean kprime(int n,int k) { int i,div=0; for(i=2;(i*i <= n) && (div<k);i++) { while(n%i==0) { n = n/i; div++; } } return div + ((n > 1)?1:0) == k; } public static void main(String[] args) ...
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#CoffeeScript
CoffeeScript
http = require 'http'   show_large_anagram_sets = (word_lst) -> anagrams = {} max_size = 0   for word in word_lst key = word.split('').sort().join('') anagrams[key] ?= [] anagrams[key].push word size = anagrams[key].length max_size = size if size > max_size   for key, variations of anagrams ...
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#Perl
Perl
use POSIX 'fmod';   sub angle { my($b1,$b2) = @_; my $b = fmod( ($b2 - $b1 + 720) , 360); $b -= 360 if $b > 180; $b += 360 if $b < -180; return $b; }   @bearings = ( 20, 45, -45, 45, -85, 90, -95, 90, -45, 125, -45, 145, 29.4803, -88.6381, -78.3251, -159.036, -70099.742338...
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#Python
Python
import urllib.request from collections import defaultdict from itertools import combinations   def getwords(url='http://www.puzzlers.org/pub/wordlists/unixdict.txt'): return list(set(urllib.request.urlopen(url).read().decode().split()))   def find_anagrams(words): anagram = defaultdict(list) # map sorted chars ...
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Nim
Nim
# Using scoped function fibI inside fib proc fib(x: int): int = proc fibI(n: int): int = if n < 2: n else: fibI(n-2) + fibI(n-1) if x < 0: raise newException(ValueError, "Invalid argument") return fibI(x)   for i in 0..4: echo fib(i)   # fibI(10) # undeclared identifier 'fibI'
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M ...
#Maple
Maple
  with(NumberTheory): pairs:=[]; for i from 1 to 20000 do for j from i+1 to 20000 do sum1:=SumOfDivisors(j)-j; sum2:=SumOfDivisors(i)-i; if sum1=i and sum2=j and i<>j then pairs:=[op(pairs),[i,j]]; printf("%a", pairs); end if; end do; end do; pairs;  
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#TI-89_BASIC
TI-89 BASIC
rcanimat() Prgm Local leftward,s,i,k,x,y false → leftward "Hello World! " → s 0 → k © last keypress found 6*3 → x © cursor position 5 → y ClrIO While k ≠ 4360 and k ≠ 277 and k ≠ 264 © QUIT,HOME,ESC keys © Handle Enter key If k = 13 Then If x ≥ 40 and x < 40+6*dim(s) and y ≥ 25...
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Vedit_macro_language
Vedit macro language
Buf_Switch(Buf_Free) Win_Create(Buf_Num, 1, 1, 2, 14) Ins_Text("Hello World! ") #2 = Cur_Pos Repeat(ALL) { if (Key_Shift_Status & 64) { BOL Block_Copy(#2-1, #2, DELETE) } else { Block_Copy(0, 1, DELETE) } EOL Update() Sleep(2) }
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de pendulum (X Y Len) (let (Angle pi/2 V 0) (call 'clear) (call 'tput "cup" Y X) (prin '+) (call 'tput "cup" 1 (+ X Len)) (until (key 25) # 25 ms (let A (*/ (sin Angle) -9.81 1.0) (inc 'V (*/ A 40)) # DT ...
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#FreeBASIC
FreeBASIC
  Function wordsOK(string1 As String, string2 As String) As boolean If Mid(string1, Len(string1), 1) = Mid(string2, 1, 1) Then Return True End If Return False End Function   Function Amb(A() As String, B() As String, C() As String, D() As String) As String Dim As Integer a2, b2, c2, d2 For a...
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Aikido
Aikido
function accumulator (sum:real) { return function(n:real) { return sum += n } }   var x = accumulator(1) x(5) println (accumulator) println (x(2.3))
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Aime
Aime
af(list l, object o) { l[0] = l[0] + o; }   main(void) { object (*f)(object);   f = af.apply(list(1));   f(5); af.apply(list(3)); o_(f(2.3), "\n");   0; }
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Action.21
Action!
DEFINE LINES_COUNT="10" DEFINE COLUMNS_COUNT="20" DEFINE WORDS_COUNT="100" DEFINE BUFFER_SIZE="2000" DEFINE LINE_WIDTH="40" DEFINE PTR="CARD"   PTR ARRAY lines(LINES_COUNT) BYTE ARRAY wordStart(WORDS_COUNT) BYTE ARRAY wordLen(WORDS_COUNT) BYTE ARRAY firstWordInLine(LINES_COUNT) BYTE ARRAY wordsInLine(LINES_COUNT) BYTE ...
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#Common_Lisp
Common Lisp
  (defclass integrator () ((input :initarg :input :writer input :reader %input) (lock :initform (bt:make-lock) :reader lock) (start-time :initform (get-internal-real-time) :reader start-time) (interval :initarg :interval :reader interval) (thread :reader thread :writer %set-thread) (area :reader area :...
http://rosettacode.org/wiki/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An Achilles number is a number that is powerful but imperfect. Na...
#Go
Go
package main   import ( "fmt" "math" "sort" )   func totient(n int) int { tot := n i := 2 for i*i <= n { if n%i == 0 { for n%i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 }...
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#Fortran
Fortran
After 1, terminates! 1 After 2, terminates! 2,1 After 2, terminates! 3,1 After 3, terminates! 4,3,1 After 2, terminates! 5,1 Perfect! 6 After 2, terminates! 7,1 After 3, terminates! 8,7,1 After 4, terminates! 9,4,3,1 After 4, terminates! ...
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Lua
Lua
empty = {} empty.foo = 1
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#M2000_Interpreter
M2000 Interpreter
  Module checkit { class alfa { x=5 } \\ a class is a global function which return a group Dim a(5)=alfa() Print a(3).x=5 For a(3) { group anyname { y=10} \\ merge anyname to this (a(3)) this=anyname } Print a(3).y=10 ...
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
  f[a]=1; f[b]=2; f[a]=3; ? f
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#Oberon-2
Oberon-2
VAR a: LONGINT; VAR b: INTEGER; b := 10; a := SYSTEM.ADR(b); (* Sets variable a to the address of variable b *)
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#OCaml
OCaml
let address_of (x:'a) : nativeint = if Obj.is_block (Obj.repr x) then Nativeint.shift_left (Nativeint.of_int (Obj.magic x)) 1 (* magic *) else invalid_arg "Can only find address of boxed values.";;   let () = let a = 3.14 in Printf.printf "%nx\n" (address_of a);; let b = ref 42 in Printf.printf "%nx...
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Crystal
Crystal
def x_minus_1_to_the(p) p.times.reduce([1]) do |ex, _| ([0_i64] + ex).zip(ex + [0]).map { |x, y| x - y } end end   def prime?(p) return false if p < 2 coeff = x_minus_1_to_the(p)[1..p//2] # only need half of coeff terms coeff.all?{ |n| n%p == 0 } end   8.times do |n| puts "(x-1)^#{n} = " + x_minus_1_...
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#F.23
F#
  // Additive Primes. Nigel Galloway: March 22nd., 2021 let rec fN g=function n when n<10->n+g |n->fN(g+n%10)(n/10) primes32()|>Seq.takeWhile((>)500)|>Seq.filter(fN 0>>isPrime)|>Seq.iter(printf "%d "); printfn ""  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#Factor
Factor
USING: formatting grouping io kernel math math.primes prettyprint sequences ;   : sum-digits ( n -- sum ) 0 swap [ 10 /mod rot + swap ] until-zero ;   499 primes-upto [ sum-digits prime? ] filter [ 9 group simple-table. nl ] [ length "Found  %d additive primes < 500.\n" printf ] bi
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#Rust
Rust
#![feature(box_patterns, box_syntax)] use self::Color::*; use std::cmp::Ordering::*;   enum Color {R,B}   type Link<T> = Option<Box<N<T>>>; struct N<T> { c: Color, l: Link<T>, val: T, r: Link<T>, }     impl<T: Ord> N<T> { fn balance(col: Color, n1: Link<T>, z: T, n2: Link<T>) -> Link<T> { So...
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#Scala
Scala
class RedBlackTree[A](implicit ord: Ordering[A]) { sealed abstract class Color case object R extends Color case object B extends Color   sealed abstract class Tree { def insert(x: A): Tree = ins(x) match { case T(_, a, y, b) => T(B, a, y, b) case E => E } def ins(x: A): Tree ...
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#GW-BASIC
GW-BASIC
10 'Almost prime 20 FOR K% = 1 TO 5 30 PRINT "k = "; K%; ":"; 40 LET I% = 2 50 LET C% = 0 60 WHILE C% < 10 70 LET AN% = I%: GOSUB 1000 80 IF ISKPRIME <> 0 THEN PRINT USING " ###"; I%;: LET C% = C% + 1 90 LET I% = I% + 1 100 WEND 110 PRINT 120 NEXT K% 130 END 995 ' Check if n (AN%) is a k (K%)...
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Common_Lisp
Common Lisp
(defun anagrams (&optional (url "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")) (let ((words (drakma:http-request url :want-stream t)) (wordsets (make-hash-table :test 'equalp))) ;; populate the wordsets and close stream (do ((word (read-line words nil nil) (read-line words nil nil))) ...
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#Phix
Phix
function tz(atom a) -- trim trailing zeroes and decimal point string res = sprintf("%16f",a) for i=length(res) to 1 by -1 do integer ch = res[i] if ch='0' or ch='.' then res[i] = ' ' end if if ch!='0' then exit end if end for return res end function proc...
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#Quackery
Quackery
[ over size over size != iff [ 2drop false ] done over sort over sort != iff [ 2drop false ] done true unrot witheach [ dip behead = if [ dip not conclude ] ] drop ] is deranged ( $ $ --> b )   $ 'rosetta/unixdict.txt' sharefile drop nest$ [] temp pu...
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface AnonymousRecursion : NSObject { } - (NSNumber *)fibonacci:(NSNumber *)n; @end   @implementation AnonymousRecursion - (NSNumber *)fibonacci:(NSNumber *)n { int i = [n intValue]; if (i < 0) @throw [NSException exceptionWithName:NSInvalidArgumentException ...
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
amicableQ[n_] := Module[{sum = Total[Most@Divisors@n]}, sum != n && n == Total[Most@Divisors@sum]]   Grid@Partition[Cases[Range[4, 20000], _?(amicableQ@# &)], 2]
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Visual_Basic
Visual Basic
VERSION 5.00 Begin VB.Form Form1 Begin VB.Timer Timer1 Interval = 250 End Begin VB.Label Label1 AutoSize = -1 'True Caption = "Hello World! " End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribut...
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "input" for Mouse   var RIGHT = true   class Animation { construct new() { Window.title = "Animation" _fore = Color.white }   init() { _text = "Hello World! " _frame = 0 Canvas.print(_text, 10, 10, _f...
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Portugol
Portugol
  programa { inclua biblioteca Matematica --> math // math library inclua biblioteca Util --> u // util library inclua biblioteca Graficos --> g // graphics library inclua biblioteca Teclado --> t // keyboard library   real accel, bx, by real theta = math.PI * 0.5 real g = 9.81 real l =...
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#Go
Go
package main   import ( "fmt" "sync" )   func ambStrings(ss []string) chan []string { c := make(chan []string) go func() { for _, s := range ss { c <- []string{s} } close(c) }() return c }   func ambChain(ss []string, cIn chan []string) chan []string { cOu...
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#ALGOL_68
ALGOL 68
MODE NUMBER = UNION(INT,REAL,COMPL);   PROC plus = (NUMBER in a, in b)NUMBER: ( CASE in a IN (INT a): CASE in b IN (INT b): a+b, (REAL b): a+b, (COMPL b): a+b ESAC, (REAL a): CASE in b IN (INT b): a+b, (REAL b): a+b, (COMPL b): a+b ESAC, (COMPL a): CASE in b IN (INT b): a+b, (REAL b): a+...
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#11l
11l
F sum_proper_divisors(n) R I n < 2 {0} E sum((1 .. n I/ 2).filter(it -> (@n % it) == 0))   V deficient = 0 V perfect = 0 V abundant = 0   L(n) 1..20000 V sp = sum_proper_divisors(n) I sp < n deficient++ E I sp == n perfect++ E I sp > n abundant++   print(‘Deficient = ’deficient) print(‘...
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Ada
Ada
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; with Ada.Text_IO; use Ada.Text_IO; with Strings_Edit; use Strings_Edit;   procedure Column_Aligner is Text : constant String := "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & NUL & "are$delineated$by$a$sin...
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#Crystal
Crystal
require "math" require "time"   # this enum allows us to specify what type of message the proc_chan received. # this trivial example only has one action, but more enum members can be added # to update the proc, or take other actions enum Action Finished # we've waited long enough, and are asking for our result # U...
http://rosettacode.org/wiki/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An Achilles number is a number that is powerful but imperfect. Na...
#J
J
achilles=: (*/ .>&1 * 1 = +./)@(1{__&q:)"0 strong=: achilles@(5&p:)
http://rosettacode.org/wiki/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An Achilles number is a number that is powerful but imperfect. Na...
#Julia
Julia
using Primes   isAchilles(n) = (p = [x[2] for x in factor(n).pe]; all(>(1), p) && gcd(p) == 1)   isstrongAchilles(n) = isAchilles(n) && isAchilles(totient(n))   function teststrongachilles(nachilles = 50, nstrongachilles = 100) # task 1 println("First $nachilles Achilles numbers:") n, found = 0, 0 while...
http://rosettacode.org/wiki/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An Achilles number is a number that is powerful but imperfect. Na...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[PowerfulNumberQ, StrongAchillesNumberQ] PowerfulNumberQ[n_Integer] := AllTrue[FactorInteger[n][[All, 2]], GreaterEqualThan[2]] AchillesNumberQ[n_Integer] := Module[{divs}, If[PowerfulNumberQ[n], divs = Divisors[n]; If[Length[divs] > 2, divs = divs[[2 ;; -2]];  !AnyTrue[Log[#, n] & /@ divs, Integ...
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#FreeBASIC
FreeBASIC
function raiseTo( bas as ulongint, power as ulongint ) as ulongint dim as ulongint result = 1, i for i = 1 to power result*=bas next i return result end function   function properDivisorSum( n as ulongint ) as ulongint dim as ulongint prod = 1, temp = n, i = 3, count = 0 while n mod 2 = 0 co...
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#MiniScript
MiniScript
empty = {} empty.foo = 1
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Morfa
Morfa
  import morfa.base;   template <T> public struct Dynamic { var data: Dict<text, T>; }   // convenience to create new Dynamic instances template <T> public property dynamic(): Dynamic<T> { return Dynamic<T>(new Dict<text,T>()); }   // introduce replacement operator for . - a quoting ` operator public operator `...
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Nim
Nim
import json {.experimental: "dotOperators".} template `.=`(js: JsonNode, field: untyped, value: untyped) = js[astToStr(field)] = %value template `.`(js: JsonNode, field: untyped): JsonNode = js[astToStr(field)] var obj = newJObject() obj.foo = "bar" echo(obj.foo) obj.key = 3 echo(obj.key)
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Objective-C
Objective-C
#import <Foundation/Foundation.h> #import <objc/runtime.h>   static void *fooKey = &fooKey; // one way to define a unique key is a pointer variable that points to itself   int main (int argc, const char *argv[]) { @autoreleasepool {   id e = [[NSObject alloc] init];   // set objc_setAssociat...
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#Oforth
Oforth
tvar: A 10 to A   tvar: B #A to B B .s [1] (Variable) #A >ok   12 B put A .s [1] (Integer) 12 [2] (Variable) #A >ok
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#Ol
Ol
'GETTING ADDRESS OF VARIABLE int a=1,b=2,c=3 print "Adrress of b: " @b 'SETTING ADDRESS OF INDIRECT (BYREF) VARIABLE int *aa,*bb,*cc @bb=@b 'setting address of bb to address of b print "Value of bb: " bb 'result: 2
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#ooRexx
ooRexx
'GETTING ADDRESS OF VARIABLE int a=1,b=2,c=3 print "Adrress of b: " @b 'SETTING ADDRESS OF INDIRECT (BYREF) VARIABLE int *aa,*bb,*cc @bb=@b 'setting address of bb to address of b print "Value of bb: " bb 'result: 2
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#OxygenBasic
OxygenBasic
'GETTING ADDRESS OF VARIABLE int a=1,b=2,c=3 print "Adrress of b: " @b 'SETTING ADDRESS OF INDIRECT (BYREF) VARIABLE int *aa,*bb,*cc @bb=@b 'setting address of bb to address of b print "Value of bb: " bb 'result: 2
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#D
D
import std.stdio, std.range, std.algorithm, std.string, std.bigint;   BigInt[] expandX1(in uint p) pure /*nothrow*/ { if (p == 0) return [1.BigInt]; typeof(return) r = [1.BigInt, BigInt(-1)]; foreach (immutable _; 1 .. p) r = zip(r~0.BigInt, 0.BigInt~r).map!(xy => xy[0]-xy[1]).array; r.reverse()...
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#Fermat
Fermat
Function Digsum(n) = digsum := 0; while n>0 do digsum := digsum + n|10; n:=n\10; od; digsum.;   nadd := 0; !!'Additive primes below 500 are';   for p=1 to 500 do if Isprime(p) and Isprime(Digsum(p)) then  !!(p,' -> ',Digsum(p)); nadd := nadd+1; fi od;   !!('There wer...
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#Forth
Forth
: prime? ( n -- ? ) here + c@ 0= ; : notprime! ( n -- ) here + 1 swap c! ;   : prime_sieve ( n -- ) here over erase 0 notprime! 1 notprime! 2 begin 2dup dup * > while dup prime? if 2dup dup * do i notprime! dup +loop then 1+ repeat 2drop ;   : digit_sum ( u -- u ) d...
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#Standard_ML
Standard ML
  datatype color = R | B datatype 'a tree = E | T of color * 'a tree * 'a * 'a tree   (** val balance = fn : color * 'a tree * 'a * 'a tree -> 'a tree *) fun balance (B, T (R, T (R,a,x,b), y, c), z, d) = T (R, T (B,a,x,b), y, T (B,c,z,d)) | balance (B, T (R, a, x, T (R,b,y,c)), z, d) = T (R, T (B,a,x,b), y, T (B,c,z,...
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#Swift
Swift
enum Color { case R, B } enum Tree<A> { case E indirect case T(Color, Tree<A>, A, Tree<A>) }   func balance<A>(input: (Color, Tree<A>, A, Tree<A>)) -> Tree<A> { switch input { case let (.B, .T(.R, .T(.R,a,x,b), y, c), z, d): return .T(.R, .T(.B,a,x,b), y, .T(.B,c,z,d)) case let (.B, .T(.R, a, x, .T(.R,b,y,c))...
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Haskell
Haskell
isPrime :: Integral a => a -> Bool isPrime n = not $ any ((0 ==) . (mod n)) [2..(truncate $ sqrt $ fromIntegral n)]   primes :: [Integer] primes = filter isPrime [2..]   isKPrime :: (Num a, Eq a) => a -> Integer -> Bool isKPrime 1 n = isPrime n isKPrime k n = any (isKPrime (k - 1)) sprimes where sprimes = map fst...
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Component_Pascal
Component Pascal
  MODULE BbtAnagrams; IMPORT StdLog,Files,Strings,Args; CONST MAXPOOLSZ = 1024;   TYPE Node = POINTER TO LIMITED RECORD; count: INTEGER; word: Args.String; desc: Node; next: Node; END;   Pool = POINTER TO LIMITED RECORD capacity,max: INTEGER; words: POINTER TO ARRAY OF Node; END;   PROCEDURE NewNode(...
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( "16" 1 "16" 1 "16" ) var al   def difAngle /# b1 b2 -- diff #/ swap - 360 mod dup 180 > if 360 - endif enddef   def test /# b1 b2 -- #/ over over difAngle >ps swap " " rot " " ps> 5 tolist al lalign ? enddef   ( "b1" " " "b2" " " "diff" ) al lalign ? "---------------- -...
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#R
R
puzzlers.dict <- readLines("http://www.puzzlers.org/pub/wordlists/unixdict.txt")   longest.deranged.anagram <- function(dict=puzzlers.dict) { anagram.groups <- function(word.group) { sorted <- sapply(lapply(strsplit(word.group,""),sort),paste, collapse="") grouped <- tapply(word.group, sorted, force, simplify...
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#OCaml
OCaml
let fib n = let rec real = function 0 -> 1 | 1 -> 1 | n -> real (n-1) + real (n-2) in if n < 0 then None else Some (real n)
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M ...
#MATLAB
MATLAB
function amicable tic N=2:1:20000; aN=[]; N(isprime(N))=[]; %erase prime numbers I=1; a=N(1); b=sum(pd(a)); while length(N)>1 if a==b %erase perfect numbers; N(N==a)=[]; a=N(1); b=sum(pd(a)); elseif b<a %the first member of an amicable pair is abundant not defective ...
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#XPL0
XPL0
include c:\cxpl\codes; int CpuReg, Dir, I, J; char Str; string 0; \use zero-terminated strings, instead of MSb set [CpuReg:= GetReg; \provides access to 8086 CPU registers \ 0123456789012 Str:= "Hello World! "; Clear; Dir:= -1; \make string initially...
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Yabasic
Yabasic
clear screen open window 400, 150 backcolor 0, 0, 0 clear window   color 250, 120, 0 texto$ = "Hello world! " l = len(texto$) dir = 1 do release$ = inkey$(.25) if mouseb(release$) = -1 then dir = -dir end if clear window text 100, 90, texto$, "modern30" if dir = 1 then texto$ = r...
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Prolog
Prolog
:- use_module(library(pce)).   pendulum :- new(D, window('Pendulum')), send(D, size, size(560, 300)), new(Line, line(80, 50, 480, 50)), send(D, display, Line), new(Circle, circle(20)), send(Circle, fill_pattern, colour(@default, 0, 0, 0)), new(Boule, circle(60)), send(Boule, fill_pattern, colour(@default, 0, ...
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#Haskell
Haskell
import Control.Monad   amb = id   joins left right = last left == head right   example = do w1 <- amb ["the", "that", "a"] w2 <- amb ["frog", "elephant", "thing"] w3 <- amb ["walked", "treaded", "grows"] w4 <- amb ["slowly", "quickly"] guard (w1 `joins` w2) guard (w2 `joins` w3) guard (w3 `joins` w4) pu...
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#AppleScript
AppleScript
on accumulator(n) -- Returns a new script object -- containing a handler. script on call(i) set n to n + i -- Returns n. end call end script end accumulator   set x to accumulator(10) log x's call(1) set y to accumulator(5) log y's call(2) log x's call(3.5) -- Event Log: (*11*) (*7*) (*14.5*)
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Argile
Argile
use std, array   let A = accumulator 42 print(A 0) print(A 1) print(A 10) print(A 100)   let B = accumulator 4.2 print(B 0) print(B 1) print(B 10.0) print(B 100.4)   ~A ; ~B (: use dbg; check mem leak :)   (: accumulator call :) =: <accumulator a> <num x> := -> (a.t) call ((a.func) as function(any)(a.t)->(a.t)) with...
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#360_Assembly
360 Assembly
* Abundant, deficient and perfect number 08/05/2016 ABUNDEFI CSECT USING ABUNDEFI,R13 set base register SAVEAR B STM-SAVEAR(R15) skip savearea DC 17F'0' savearea STM STM R14,R12,12(R13) save registers ST R13,4(R15) link backward ...
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Aime
Aime
data b; file f; text n, t; list c, r, s; integer a, i, k, m, w;   b = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" "are$delineated$by$a$single$'dollar'$character,$write$a$program\n" "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" "column$are$separated$by$at$least$on...
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#D
D
import core.thread; import std.datetime; import std.math; import std.stdio;   void main() { auto func = (double t) => sin(cast(double) PI * t); Integrator integrator = new Integrator(func); Thread.sleep(2000.msecs);   integrator.setFunc(t => 0.0); Thread.sleep(500.msecs);   integrator.stop(); ...
http://rosettacode.org/wiki/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An Achilles number is a number that is powerful but imperfect. Na...
#Perl
Perl
use strict; use warnings; use feature <say current_sub>; use experimental 'signatures'; use List::AllUtils <max head uniqint>; use ntheory <is_square_free is_power euler_phi>; use Math::AnyNum <:overload idiv iroot ipow is_coprime>;   sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_...
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#Go
Go
package main   import ( "fmt" "math" "strings" )   const threshold = uint64(1) << 47   func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 }   func contains(s []uint64, search uint64) bool { return indexOf(s,...
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Octave
Octave
  % Given struct "test" test.b=1; test = setfield (test, "c", 3);  
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#ooRexx
ooRexx
  d = .dynamicvar~new d~foo = 123 say d~foo   d2 = .dynamicvar2~new d~bar = "Fred" say d~bar   -- a class that allows dynamic variables. Since this is a mixin, this -- capability can be added to any class using multiple inheritance ::class dynamicvar MIXINCLASS object ::method init expose variables variables = .di...
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#OxygenBasic
OxygenBasic
  '================= class fleximembers '=================   indexbase 0 bstring buf, *varl sys dp,en   method addVar(string name,dat) sys le=len buf if dp+16>le then buf+=nuls 0x100 : le+=0x100 : end if @varl=?buf varl[en]=name varl[en+1]=dat dp+=2*sizeof sys en+=2 'next slot end method   metho...
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#Panoramic
Panoramic
  == Get ==   adr(variable)   Example:   dim a print adr(a)   == Set ==   Whether Panoramic is able to set the value of a variable may depend on what is meant by that. Panoramic implements the poke command to set a byte from a value of 0 to 255 (inclusive). Panoramic also implements the peek command to get the value of...