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/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#PureBasic
PureBasic
Procedure.d Gamma(x.d) ; AKJ 01-May-10 ; Complete Gamma function for x>0 and x<2 (approx) ; Extended outside this range via: Gamma(x+1) = x*Gamma(x) ; Based on http://rosettacode.org/wiki/Gamma_function [Ada] Protected Dim A.d(28) A(0) = 1.0 A(1) = 0.5772156649015328606 A(2) =-0.6558780715202538811 A(3) =-0.0420026350340952355 A(4) = 0.1665386113822914895 A(5) =-0.0421977345555443368 ; was ...33675 A(6) =-0.0096219715278769736 A(7) = 0.0072189432466630995 A(8) =-0.0011651675918590651 A(9) =-0.0002152416741149510 A(10) = 0.0001280502823881162 A(11) =-0.0000201348547807882 A(12) =-0.0000012504934821427 A(13) = 0.0000011330272319817 A(14) =-0.0000002056338416978 A(15) = 0.0000000061160951045 A(16) = 0.0000000050020076445 A(17) =-0.0000000011812745705 A(18) = 0.0000000001043426712 A(19) = 0.0000000000077822634 A(20) =-0.0000000000036968056 A(21) = 0.0000000000005100370 A(22) =-0.0000000000000205833 A(23) =-0.0000000000000053481 A(24) = 0.0000000000000012268 A(25) =-0.0000000000000001181 A(26) = 0.0000000000000000012 A(27) = 0.0000000000000000014 A(28) =-0.0000000000000000002 ;A(29) = 0.00000000000000000002 Protected y.d, Prod.d, Sum.d, N If x<=0.0: ProcedureReturn 0.0: EndIf ; Error y = x-1.0: Prod = 1.0 While y>=1.0 Prod*y: y-1.0 ; Recurse using Gamma(x+1) = x*Gamma(x) Wend Sum= A(28) For N = 27 To 0 Step -1 Sum*y+A(N) Next N If Sum=0.0: ProcedureReturn Infinity(): EndIf ProcedureReturn Prod / Sum EndProcedure   Procedure.d GammLn(x.d) ; AKJ 01-May-10 ; Returns Ln(Gamma()) or 0 on error ; Based on Numerical Recipes gamma.h Protected j, tmp.d, y.d, ser.d Protected Dim cof.d(13) cof(0) = 57.1562356658629235 cof(1) = -59.5979603554754912 cof(2) = 14.1360979747417471 cof(3) = -0.491913816097620199 cof(4) = 0.339946499848118887e-4 cof(5) = 0.465236289270485756e-4 cof(6) = -0.983744753048795646e-4 cof(7) = 0.158088703224912494e-3 cof(8) = -0.210264441724104883e-3 cof(9) = 0.217439618115212643e-3 cof(10) = -0.164318106536763890e-3 cof(11) = 0.844182239838527433e-4 cof(12) = -0.261908384015814087e-4 cof(13) = 0.368991826595316234e-5 If x<=0: ProcedureReturn 0: EndIf ; Bad argument y = x tmp = x+5.2421875 tmp = (x+0.5)*Log(tmp)-tmp ser = 0.999999999999997092 For j=0 To 13 y + 1: ser + cof(j)/y Next j ProcedureReturn tmp+Log(2.5066282746310005*ser/x) EndProcedure   Procedure Factorial(x) ; AKJ 01-May-10 ProcedureReturn Gamma(x+1) EndProcedure
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Snobol
Snobol
&ALPHABET ('a' LEN(25)) . OUTPUT ;* Works in ASCII but not EBCDIC.
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#SPL
SPL
> i, 1..26 d = [i+96,0] a[i] = #.str(d) < 'now A is an array of letters a..z   > i, 1..#.size(a,1) #.output(a[i],#.rs) <
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
#Prolog
Prolog
:- write('Hello world!'), nl.
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Order
Order
#include <order/interpreter.h>   #define ORDER_PP_DEF_8comp ORDER_PP_FN( \ 8fn(8F, 8G, 8fn(8X, 8ap(8F, 8ap(8G, 8X)))) )
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Oz
Oz
declare fun {Compose F G} fun {$ X} {F {G X}} end end   SinAsin = {Compose Float.sin Float.asin} in {Show {SinAsin 0.5}}
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Scheme
Scheme
  (import (scheme base) (scheme file) (scheme inexact) (scheme write))   (define *scale* 10) ; controls overall size of tree (define *split* 20) ; controls angle of split (in degrees)   ;; construct lines for tree as list of 5-tuples (x1 y1 x2 y2 depth) ;; - x1 y1 is start point ;; - angle of this line, in radians ;; - depth, depth within tree (controls length of line) (define (create-tree x1 y1 angle depth) (define (degrees->radians d) (let ((pi 3.14159265358979323846264338327950288419716939937510582097)) (* d pi 1/180))) ; (if (zero? depth) '() (let ((x2 (+ x1 (* (cos (degrees->radians angle)) depth *scale*))) (y2 (+ y1 (* (sin (degrees->radians angle)) depth *scale*)))) (append (list (map truncate (list x1 y1 x2 y2 depth))) (create-tree x2 y2 (- angle *split*) (- depth 1)) (create-tree x2 y2 (+ angle *split*) (- depth 1))))))   ;; output the tree to an eps file (define (output-tree-as-eps filename tree) (when (file-exists? filename) (delete-file filename)) (with-output-to-file filename (lambda () (display "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 800 800\n")   ;; add each line - sets linewidth based on depth in tree (for-each (lambda (line) (display (string-append "newpath\n" (number->string (list-ref line 0)) " " (number->string (list-ref line 1)) " " "moveto\n" (number->string (list-ref line 2)) " " (number->string (list-ref line 3)) " " "lineto\n" (number->string (truncate (/ (list-ref line 4) 2))) " setlinewidth\n" "stroke\n" ))) tree) (display "\n%%EOF"))))   (output-tree-as-eps "fractal.eps" (create-tree 400 200 90 9))  
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Red
Red
Red ["Fractran"]   inp: ask "please enter list of fractions, or input file name: " if exists? inpf: to-file inp [inp: read inpf]   digit: charset "0123456789" frac: [copy p [some digit] #"/" copy q [some digit] keep (as-pair to-integer p to-integer q)] code: parse inp [collect [frac some [[some " "] frac]]]   n: to-integer ask "please enter starting number n: " x: to-integer ask "please enter the number of terms, hit return for no limit: " l: length? code loop x [ forall code [ c: code/1 if n % c/y = 0 [ print n: n / c/y * c/x code: head code break ] if l = index? code [halt] ] ]
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#CLU
CLU
multiply = proc (a, b: int) returns (int) return(a * b) end multiply
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Python
Python
_a = ( 1.00000000000000000000, 0.57721566490153286061, -0.65587807152025388108, -0.04200263503409523553, 0.16653861138229148950, -0.04219773455554433675, -0.00962197152787697356, 0.00721894324666309954, -0.00116516759185906511, -0.00021524167411495097, 0.00012805028238811619, -0.00002013485478078824, -0.00000125049348214267, 0.00000113302723198170, -0.00000020563384169776, 0.00000000611609510448, 0.00000000500200764447, -0.00000000118127457049, 0.00000000010434267117, 0.00000000000778226344, -0.00000000000369680562, 0.00000000000051003703, -0.00000000000002058326, -0.00000000000000534812, 0.00000000000000122678, -0.00000000000000011813, 0.00000000000000000119, 0.00000000000000000141, -0.00000000000000000023, 0.00000000000000000002 ) def gamma (x): y = float(x) - 1.0; sm = _a[-1]; for an in _a[-2::-1]: sm = sm * y + an; return 1.0 / sm;     if __name__ == '__main__': for i in range(1,11): print "  %20.14e" % gamma(i/3.0)  
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Standard_ML
Standard ML
val lowercase_letters = List.tabulate (26, fn x => chr (x + ord #"a"));
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Stata
Stata
// built-in: lowercase and uppercase letters display c(alpha) display c(ALPHA)   // generate a variable with the letters clear set obs 26 gen a=char(96+_n)   // or in Mata mata char(97..122) end
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
#PROMAL
PROMAL
  program hello include library begin output "Hello world!" end  
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#PARI.2FGP
PARI/GP
compose(f, g)={ x -> f(g(x)) };   compose(x->sin(x),x->cos(x)(1)
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Pascal
Pascal
sub compose { my ($f, $g) = @_;   sub { $f -> ($g -> (@_)) }; }   use Math::Trig; print compose(sub {sin $_[0]}, \&asin)->(0.5), "\n";
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Scilab
Scilab
trunk = 1; //trunk length ratio = 0.8; //size ratio between two consecutive branches depth = 9; //final number of branch levels orign = 0; //origin of the tree (should be complex) angle = 45*%pi/180; //angle between two branches [rad] trunk_angle = 90*%pi/180; //angle between trunk and X-axis [rad]   right_angle = angle/2; //angles to the right or to the left left_angle = 0.8*angle; //can be set independently or //as function of 'angle'   //L-system definition: //Alphabet: FBD[]+- //F: go forward B: go backwards //[: start new branch ]: end current branch //+: branch to the right -: branch to the left //D: double line (forward then backward) //Axiom: D //Rule: D -> F[+D-D]B   //L-system sentence generation sentence = 'D' rule = 'F[+D-D]B'; for i=1:depth sentence = strsubst(sentence,'D',rule); end sentence = strsplit(sentence)';   //Empty tree tree_size = 1.0... + length(find(sentence=='F'|sentence=='B'))... + 2 * length(find(sentence=='D')); tree=zeros(tree_size,1);   //Drawing the tree branch_level = 0; curr_angle = trunk_angle; curr_pos = 1;   for ind = 1:size(sentence,'c') charac = sentence(ind);   select charac case 'F' then //Draw line forward tree(curr_pos+1) = tree(curr_pos)... + trunk * ratio^branch_level * exp(curr_angle*%i); curr_pos = curr_pos + 1;   case 'B' then //Draw line backwards tree(curr_pos+1) = tree(curr_pos)... + trunk * ratio^branch_level * exp((%pi+curr_angle)*%i); curr_pos = curr_pos + 1;   case '[' then //New branch branch_level = branch_level + 1;   case '+' then //Turn right curr_angle = curr_angle - right_angle;   case '-' then //Turn left curr_angle = curr_angle + right_angle + left_angle;   case ']' then //End of branch branch_level = branch_level - 1; curr_angle = curr_angle - left_angle;   case 'D' then //Double line tree(curr_pos+1) = tree(curr_pos)... + trunk * ratio^branch_level * exp(curr_angle*%i); tree(curr_pos+2) = tree(curr_pos+1)... + trunk * ratio^branch_level * exp((%pi+curr_angle)*%i); curr_pos = curr_pos + 2; end end   scf(); clf(); xname('Fractal tree: '+string(depth)+' levels') plot2d(real(tree),imag(tree),14); set(gca(),'isoview','on'); set(gca(),'axes_visible',['off','off','off']);
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i"; include "draw.s7i"; include "keybd.s7i";   const float: DEG_TO_RAD is PI / 180.0;   const proc: drawTree (in integer: x1, in integer: y1, in float: angle, in integer: depth) is func local var integer: x2 is 0; var integer: y2 is 0; begin if depth <> 0 then x2 := x1 + trunc(cos(angle * DEG_TO_RAD) * flt(depth * 10)); y2 := y1 + trunc(sin(angle * DEG_TO_RAD) * flt(depth * 10)); lineTo(x1, y1, x2, y2, white); drawTree(x2, y2, angle - 20.0, depth - 1); drawTree(x2, y2, angle + 20.0, depth - 1); end if; end func;   const proc: main is func begin screen(600, 500); clear(curr_win, black); KEYBOARD := GRAPH_KEYBOARD; drawTree(300, 470, -90.0, 9); ignore(getc(KEYBOARD)); end func;
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#REXX
REXX
/*REXX program runs FRACTRAN for a given set of fractions and from a specified N. */ numeric digits 2000 /*be able to handle larger numbers. */ parse arg N terms fracs /*obtain optional arguments from the CL*/ if N=='' | N=="," then N= 2 /*Not specified? Then use the default.*/ if terms=='' | terms=="," then terms= 100 /* " " " " " " */ if fracs='' then fracs= "17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23,", '77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1' /* [↑] The default for the fractions. */ f= space(fracs, 0) /*remove all blanks from the FRACS list*/ do #=1 while f\==''; parse var f n.# "/" d.# ',' f end /*#*/ /* [↑] parse all the fractions in list*/ #= # - 1 /*the number of fractions just found. */ say # 'fractions:' fracs /*display number and actual fractions. */ say 'N is starting at ' N /*display the starting number N. */ say terms ' terms are being shown:' /*display a kind of header/title. */   do j=1 for terms /*perform the DO loop for each term. */ do k=1 for # /* " " " " " " fraction*/ if N // d.k \== 0 then iterate /*Not an integer? Then ignore it. */ cN= commas(N); L= length(cN) /*maybe insert commas into N; get len.*/ say right('term' commas(j), 44) "──► " right(cN, max(15, L)) /*show Nth term & N*/ N= N  % d.k * n.k /*calculate next term (use %≡integer ÷)*/ leave /*go start calculating the next term. */ end /*k*/ /* [↑] if an integer, we found a new N*/ end /*j*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. myTest. DATA DIVISION. WORKING-STORAGE SECTION. 01 x PIC 9(3) VALUE 3. 01 y PIC 9(3) VALUE 2. 01 z PIC 9(9). PROCEDURE DIVISION. CALL "myMultiply" USING BY CONTENT x, BY CONTENT y, BY REFERENCE z. DISPLAY z. STOP RUN. END PROGRAM myTest.   IDENTIFICATION DIVISION. PROGRAM-ID. myMultiply. DATA DIVISION. LINKAGE SECTION. 01 x PIC 9(3). 01 y PIC 9(3). 01 z PIC 9(9). PROCEDURE DIVISION USING x, y, z. MULTIPLY x BY y GIVING z. EXIT PROGRAM. END PROGRAM myMultiply.
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#R
R
stirling <- function(z) sqrt(2*pi/z) * (exp(-1)*z)^z   nemes <- function(z) sqrt(2*pi/z) * (exp(-1)*(z + (12*z - (10*z)^-1)^-1))^z   lanczos <- function(z) { if(length(z) > 1) { sapply(z, lanczos) } else { g <- 7 p <- c(0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7) z <- as.complex(z) if(Re(z) < 0.5) { pi / (sin(pi*z) * lanczos(1-z)) } else { z <- z - 1 x <- p[1] + sum(p[-1]/seq.int(z+1, z+g+1)) tt <- z + g + 0.5 sqrt(2*pi) * tt^(z+0.5) * exp(-tt) * x } } }   spouge <- function(z, a=49) { if(length(z) > 1) { sapply(z, spouge) } else { z <- z-1 k <- seq.int(1, a-1) ck <- rep(c(1, -1), len=a-1) / factorial(k-1) * (a-k)^(k-0.5) * exp(a-k) (z + a)^(z+0.5) * exp(-z - a) * (sqrt(2*pi) + sum(ck/(z+k))) } }   # Checks z <- (1:10)/3 all.equal(gamma(z), stirling(z)) # Mean relative difference: 0.07181942 all.equal(gamma(z), nemes(z)) # Mean relative difference: 0.003460549 all.equal(as.complex(gamma(z)), lanczos(z)) # TRUE all.equal(gamma(z), spouge(z)) # TRUE data.frame(z=z, stirling=stirling(z), nemes=nemes(z), lanczos=lanczos(z), spouge=spouge(z), builtin=gamma(z))
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Racket
Racket
#lang racket (define (gamma number) (if (> 1/2 number) (/ pi (* (sin (* pi number)) (gamma (- 1.0 number)))) (let ((n (sub1 number)) (c '(0.99999999999980993 676.5203681218851 -1259.1392167224028 771.32342877765313 -176.61502916214059 12.507343278686905 -0.13857109526572012 9.9843695780195716e-6 1.5056327351493116e-7))) (* (sqrt (* pi 2)) (expt (+ n 7 0.5) (+ n 0.5)) (exp (- (+ n 7 0.5))) (+ (car c) (apply + (for/list ((i (in-range (length (cdr c)))) (x (in-list (cdr c)))) (/ x (+ 1 n i)))))))))   (map gamma '(0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0)) ;-> ;'(9.513507698668736 ; 4.590843711998802 ; 2.9915689876875904 ; 2.218159543757687 ; 1.7724538509055159 ; 1.489192248812818 ; 1.2980553326475577 ; 1.1642297137253037 ; 1.068628702119319 ; 1.0)
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#SuperCollider
SuperCollider
  (97..122).asAscii; // This example unfortunately throws an error // for me when running it on version 3.10.2   // Apparently, the message 'asAscii' cannot be understood by // an Array, so I used the message 'collect' to apply the function // enclosed in {} to each individual element of the Array, // passing them the message 'asAscii':   (97..122).collect({|asciiCode| asciiCode.asAscii});   // Instead of writing the ascii codes directly as numbers, // one could also pass the chars a and z the message 'ascii' to convert // them to ascii codes – perhaps making the code a bit clearer:   ($a.ascii..$z.ascii).collect({|asciiCode| asciiCode.asAscii});   // both examples output [ a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z ]      
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Swift
Swift
var letters = [Character]()   for i in 97...122 { let char = Character(UnicodeScalar(i)) letters.append(char) }
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
#PSQL
PSQL
EXECUTE BLOCK RETURNS(S VARCHAR(40)) AS BEGIN S = 'Hello world!'; SUSPEND; END
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Perl
Perl
sub compose { my ($f, $g) = @_;   sub { $f -> ($g -> (@_)) }; }   use Math::Trig; print compose(sub {sin $_[0]}, \&asin)->(0.5), "\n";
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Phix
Phix
sequence ctable = {} function compose(integer f, integer g) ctable = append(ctable,{f,g}) return length(ctable) end function function call_composite(integer f, atom x) integer g {f,g} = ctable[f] return call_func(f,{call_func(g,{x})}) end function function plus1(atom x) return x+1 end function function halve(atom x) return x/2 end function constant m = compose(routine_id("halve"),routine_id("plus1")) ?call_composite(m,1) -- displays 1 ?call_composite(m,4) -- displays 2.5
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Sidef
Sidef
func tree(img, x, y, scale=6/10, len=400, angle=270) {   len < 1 && return()   img.moveTo(x, y) img.angle(angle) img.line(len)   var (x1, y1) = img.curPos tree(img, x1, y1, scale, len*scale, angle+35) tree(img, x1, y1, scale, len*scale, angle-35) }   require('GD::Simple')   var (width=1000, height=1000) var img = %s|GD::Simple|.new(width, height) img.fgcolor('black') img.penSize(1, 1)   tree(img, width/2, height)   File('tree.png').write(img.png, :raw)
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Ruby
Ruby
ar = %w[17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1] FractalProgram = ar.map(&:to_r) #=> array of rationals   Runner = Enumerator.new do |y| num = 2 loop{ y << num *= FractalProgram.detect{|f| (num*f).denominator == 1} } end   prime_generator = Enumerator.new do |y| Runner.each do |num| l = Math.log2(num) y << l.to_i if l.floor == l end end   # demo p Runner.take(20).map(&:numerator) p prime_generator.take(20)
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Coco
Coco
multiply = -> @@0 * @@1
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Raku
Raku
sub Γ(\z) { constant g = 9; z < .5 ?? pi/ sin(pi * z) / Γ(1 - z) !! sqrt(2*pi) * (z + g - 1/2)**(z - 1/2) * exp(-(z + g - 1/2)) * [+] < 1.000000000000000174663 5716.400188274341379136 -14815.30426768413909044 14291.49277657478554025 -6348.160217641458813289 1301.608286058321874105 -108.1767053514369634679 2.605696505611755827729 -0.7423452510201416151527e-2 0.5384136432509564062961e-7 -0.4023533141268236372067e-8 > Z* 1, |map 1/(z + *), 0..* }   say Γ($_) for 1/3, 2/3 ... 10/3;
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Tcl
Tcl
set alpha {a b c d e f g h i j k l m n o p q r s t u v w x y z}
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#UNIX_Shell
UNIX Shell
lower=({a..z})
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
#Pure
Pure
  using system;   puts "Hello world!\n" ;  
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Phixmonti
Phixmonti
def *2 2 * enddef def ++ 1 + enddef def composite swap exec swap exec enddef   getid ++ getid *2 3 composite print /# result: 7 #/
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#PHP
PHP
<?php function compose($f, $g) { return function($x) use ($f, $g) { return $f($g($x)); }; }   $trim_strlen = compose('strlen', 'trim'); echo $result = $trim_strlen(' Test '), "\n"; // prints 4 ?>
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Smalltalk
Smalltalk
  Object subclass: #FractalTree instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'RosettaCode'  
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#SVG
SVG
<?xml version="1.0" standalone="yes"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="320"> <style type="text/css"><![CDATA[ line { stroke: black; stroke-width: .05; } circle { fill: black; } ]]></style>   <defs> <g id="stem"> <line x1="0" y1="0" x2="0" y2="-1"/> </g>   <g id="l0"><use xlink:href="#stem"/></g> <!-- These are identical except for the id and href. --> <g id="l1"> <use xlink:href="#l0" transform="translate(0, -1) rotate(-35) scale(.7)"/> <use xlink:href="#l0" transform="translate(0, -1) rotate(+35) scale(.7)"/> <use xlink:href="#stem"/></g> <g id="l2"> <use xlink:href="#l1" transform="translate(0, -1) rotate(-35) scale(.7)"/> <use xlink:href="#l1" transform="translate(0, -1) rotate(+35) scale(.7)"/> <use xlink:href="#stem"/></g> <g id="l3"> <use xlink:href="#l2" transform="translate(0, -1) rotate(-35) scale(.7)"/> <use xlink:href="#l2" transform="translate(0, -1) rotate(+35) scale(.7)"/> <use xlink:href="#stem"/></g> <g id="l4"> <use xlink:href="#l3" transform="translate(0, -1) rotate(-35) scale(.7)"/> <use xlink:href="#l3" transform="translate(0, -1) rotate(+35) scale(.7)"/> <use xlink:href="#stem"/></g> <g id="l5"> <use xlink:href="#l4" transform="translate(0, -1) rotate(-35) scale(.7)"/> <use xlink:href="#l4" transform="translate(0, -1) rotate(+35) scale(.7)"/> <use xlink:href="#stem"/></g> <g id="l6"> <use xlink:href="#l5" transform="translate(0, -1) rotate(-35) scale(.7)"/> <use xlink:href="#l5" transform="translate(0, -1) rotate(+35) scale(.7)"/> <use xlink:href="#stem"/></g> <g id="l7"> <use xlink:href="#l6" transform="translate(0, -1) rotate(-35) scale(.7)"/> <use xlink:href="#l6" transform="translate(0, -1) rotate(+35) scale(.7)"/> <use xlink:href="#stem"/></g> <g id="l8"> <use xlink:href="#l7" transform="translate(0, -1) rotate(-35) scale(.7)"/> <use xlink:href="#l7" transform="translate(0, -1) rotate(+35) scale(.7)"/> <use xlink:href="#stem"/></g> <g id="l9"> <use xlink:href="#l8" transform="translate(0, -1) rotate(-35) scale(.7)"/> <use xlink:href="#l8" transform="translate(0, -1) rotate(+35) scale(.7)"/> <use xlink:href="#stem"/></g> </defs>   <g transform="translate(200, 320) scale(100)"> <use xlink:href="#l9"/> </g>   </svg>
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Scala
Scala
class TestFractran extends FunSuite { val program = Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1") val expect = List(2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, 910, 170, 156, 132)   test("find first fifteen fractran figures") { assert((program .execute(2) take 15 toList) === expect) } }   object Fractran { val pattern = """\s*(\d+)\s*/\s*(\d+)\s*""".r def parse(m: Match) = ((m group 1).toInt, (m group 2).toInt) def apply(program: String) = new Fractran( pattern.findAllMatchIn(program).map(parse).toList) }   class Fractran(val numDem: List[(Int,Int)]) { def execute(value: Int) = unfold(value) { v => numDem indexWhere(v % _._2 == 0) match { case i if i > -1 => Some(v, numDem(i)._1 * v / numDem(i)._2) case _ => None } } }
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#CoffeeScript
CoffeeScript
multiply = (a, b) -> a * b
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#REXX
REXX
/*REXX program calculates GAMMA using the Taylor series coefficients; ≈80 decimal digits*/ /*The GAMMA function symbol is the Greek capital letter: Γ */ numeric digits 90 /*be able to handle extended precision.*/ parse arg LO HI . /*allow specification of gamma arg/args*/ /* [↓] either show a range or a ··· */ do j=word(LO 1, 1) to word(HI LO 9, 1) /* ··· single gamma value.*/ say 'gamma('j") =" gamma(j) /*compute gamma of J and display value.*/ end /*j*/ /* [↑] default LO is one; HI is nine.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ gamma: procedure; parse arg x; xm=x-1; sum=0 /*coefficients thanks to: Arne Fransén & Staffan Wrigge.*/ #.1 = 1 /* [↓] #.2 is the Euler-Mascheroni constant. */ #.2 = 0.57721566490153286060651209008240243104215933593992359880576723488486772677766467 #.3 = -0.65587807152025388107701951514539048127976638047858434729236244568387083835372210 #.4 = -0.04200263503409523552900393487542981871139450040110609352206581297618009687597599 #.5 = 0.16653861138229148950170079510210523571778150224717434057046890317899386605647425 #.6 = -0.04219773455554433674820830128918739130165268418982248637691887327545901118558900 #.7 = -0.00962197152787697356211492167234819897536294225211300210513886262731167351446074 #.8 = 0.00721894324666309954239501034044657270990480088023831800109478117362259497415854 #.9 = -0.00116516759185906511211397108401838866680933379538405744340750527562002584816653 #.10 = -0.00021524167411495097281572996305364780647824192337833875035026748908563946371678 #.11 = 0.00012805028238811618615319862632816432339489209969367721490054583804120355204347 #.12 = -0.00002013485478078823865568939142102181838229483329797911526116267090822918618897 #.13 = -0.00000125049348214267065734535947383309224232265562115395981534992315749121245561 #.14 = 0.00000113302723198169588237412962033074494332400483862107565429550539546040842730 #.15 = -0.00000020563384169776071034501541300205728365125790262933794534683172533245680371 #.16 = 0.00000000611609510448141581786249868285534286727586571971232086732402927723507435 #.17 = 0.00000000500200764446922293005566504805999130304461274249448171895337887737472132 #.18 = -0.00000000118127457048702014458812656543650557773875950493258759096189263169643391 #.19 = 0.00000000010434267116911005104915403323122501914007098231258121210871073927347588 #.20 = 0.00000000000778226343990507125404993731136077722606808618139293881943550732692987 #.21 = -0.00000000000369680561864220570818781587808576623657096345136099513648454655443000 #.22 = 0.00000000000051003702874544759790154813228632318027268860697076321173501048565735 #.23 = -0.00000000000002058326053566506783222429544855237419746091080810147188058196444349 #.24 = -0.00000000000000534812253942301798237001731872793994898971547812068211168095493211 #.25 = 0.00000000000000122677862823826079015889384662242242816545575045632136601135999606 #.26 = -0.00000000000000011812593016974587695137645868422978312115572918048478798375081233 #.27 = 0.00000000000000000118669225475160033257977724292867407108849407966482711074006109 #.28 = 0.00000000000000000141238065531803178155580394756670903708635075033452562564122263 #.29 = -0.00000000000000000022987456844353702065924785806336992602845059314190367014889830 #.30 = 0.00000000000000000001714406321927337433383963370267257066812656062517433174649858 #.31 = 0.00000000000000000000013373517304936931148647813951222680228750594717618947898583 #.32 = -0.00000000000000000000020542335517666727893250253513557337960820379352387364127301 #.33 = 0.00000000000000000000002736030048607999844831509904330982014865311695836363370165 #.34 = -0.00000000000000000000000173235644591051663905742845156477979906974910879499841377 #.35 = -0.00000000000000000000000002360619024499287287343450735427531007926413552145370486 #.36 = 0.00000000000000000000000001864982941717294430718413161878666898945868429073668232 #.37 = -0.00000000000000000000000000221809562420719720439971691362686037973177950067567580 #.38 = 0.00000000000000000000000000012977819749479936688244144863305941656194998646391332 #.39 = 0.00000000000000000000000000000118069747496652840622274541550997151855968463784158 #.40 = -0.00000000000000000000000000000112458434927708809029365467426143951211941179558301 #.41 = 0.00000000000000000000000000000012770851751408662039902066777511246477487720656005 #.42 = -0.00000000000000000000000000000000739145116961514082346128933010855282371056899245 #.43 = 0.00000000000000000000000000000000001134750257554215760954165259469306393008612196 #.44 = 0.00000000000000000000000000000000004639134641058722029944804907952228463057968680 #.45 = -0.00000000000000000000000000000000000534733681843919887507741819670989332090488591 #.46 = 0.00000000000000000000000000000000000032079959236133526228612372790827943910901464 #.47 = -0.00000000000000000000000000000000000000444582973655075688210159035212464363740144 #.48 = -0.00000000000000000000000000000000000000131117451888198871290105849438992219023663 #.49 = 0.00000000000000000000000000000000000000016470333525438138868182593279063941453996 #.50 = -0.00000000000000000000000000000000000000001056233178503581218600561071538285049997 #.51 = 0.00000000000000000000000000000000000000000026784429826430494783549630718908519485 #.52 = 0.00000000000000000000000000000000000000000002424715494851782689673032938370921241 #=52; do k=# by -1 for # sum=sum*xm + #.k end /*k*/ return 1/sum
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ursa
Ursa
decl int i decl string low for (set i (ord "a")) (< i (+ (ord "z") 1)) (inc i) set low (+ low (chr i)) end for out low endl console
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#VBA
VBA
  Option Explicit   Sub Main_Lower_Case_Ascii_Alphabet() Dim Alpha() As String   Alpha = Alphabet(97, 122) Debug.Print Join(Alpha, ", ") End Sub   Function Alphabet(FirstAscii As Byte, LastAscii As Byte) As String() Dim strarrTemp() As String, i&   ReDim strarrTemp(0 To LastAscii - FirstAscii) For i = FirstAscii To LastAscii strarrTemp(i - FirstAscii) = Chr(i) Next Alphabet = strarrTemp Erase strarrTemp End Function  
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
#PureBasic
PureBasic
OpenConsole() PrintN("Hello world!") Input() ; Wait for enter
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#PicoLisp
PicoLisp
(de compose (F G) (curry (F G) (X) (F (G X)) ) )
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#PostScript
PostScript
  /compose { % f g -> { g f } [ 3 1 roll exch  % procedures are not executed when encountered directly  % insert an 'exec' after procedures, but not after operators 1 index type /operatortype ne { /exec cvx exch } if dup type /operatortype ne { /exec cvx } if ] cvx } def   /square { dup mul } def /plus1 { 1 add } def /sqPlus1 /square load /plus1 load compose def  
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Swift
Swift
extension CGFloat { func degrees_to_radians() -> CGFloat { return CGFloat(M_PI) * self / 180.0 } }   extension Double { func degrees_to_radians() -> Double { return Double(M_PI) * self / 180.0 } }     class Tree: UIView {     func drawTree(x1: CGFloat, y1: CGFloat, angle: CGFloat, depth:Int){ if depth == 0 { return } let ang = angle.degrees_to_radians() let x2:CGFloat = x1 + ( cos(ang) as CGFloat) * CGFloat(depth) * (self.frame.width / 60) let y2:CGFloat = y1 + ( sin(ang) as CGFloat) * CGFloat(depth) * (self.frame.width / 60)   let line = drawLine(x1, y1: y1, x2: x2, y2: y2)   line.stroke() drawTree(x2, y1: y2, angle: angle - 20, depth: depth - 1) drawTree(x2, y1: y2, angle: angle + 20, depth: depth - 1) }   func drawLine(x1:CGFloat, y1:CGFloat, x2:CGFloat, y2:CGFloat) -> UIBezierPath {   let path = UIBezierPath() path.moveToPoint(CGPoint(x: x1,y: y1)) path.addLineToPoint(CGPoint(x: x2,y: y2)) path.lineWidth = 1 return path }   override func drawRect(rect: CGRect) {   let color = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0) color.set() drawTree(self.frame.width / 2 , y1: self.frame.height * 0.8, angle: -90 , depth: 9 ) } }     let tree = Tree(frame: CGRectMake(0, 0, 300, 300)) tree  
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Standard_ML
Standard ML
open XWindows; open Motif;   fun toI {x=x,y=y} = {x=Real.toInt IEEEReal.TO_NEAREST x,y=Real.toInt IEEEReal.TO_NEAREST y}  ;     fun drawOnTop win usegc ht hs {x=l1,y=l2} {x=r1,y=r2} = let val xy = {x=l1 - ht * (l2-r2) , y = l2 - ht * (r1-l1) } val zt = {x=r1 - ht * (l2-r2) , y= r2 - ht * (r1-l1) } val ab = {x= ( (#x xy + #x zt) + hs * (#y zt - #y xy ) )/2.0 , y = ( (#y zt + #y xy) - hs * (#x zt - #x xy )) /2.0 } in   if abs (l1 - #x xy ) < 0.9 andalso abs (l2 - #y xy ) < 0.9 then XFlush (XtDisplay win) else (XFillPolygon (XtWindow win) usegc [ (XPoint o toI) {x=l1,y=l2}, (XPoint o toI ) xy , (XPoint o toI ) ab , (XPoint o toI ) zt , (XPoint o toI ) {x=r1,y=r2} ] Convex CoordModeOrigin  ; drawOnTop win usegc (0.87*ht) hs xy ab ; drawOnTop win usegc (0.93*ht) hs ab zt )   end ;     val demoWindow = fn () => let val shell = XtAppInitialise "" "tree" "top" [] [ XmNwidth 800, XmNheight 650] ; val main = XmCreateMainWindow shell "main" [ XmNmappedWhenManaged true ]  ; val canvas = XmCreateDrawingArea main "drawarea" [ XmNwidth 800, XmNheight 650] ; val usegc = DefaultGC (XtDisplay canvas) ; in   XtSetCallbacks canvas [ (XmNexposeCallback , (fn (w,c,t) => ( drawOnTop canvas usegc 8.0 0.85 {x=385.0,y=645.0} {x=415.0,y=645.0} ; t) ) ) ] XmNarmCallback ; XtManageChild canvas ; XtManageChild main  ; XtRealizeWidget shell   end ;   demoWindow ();
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Scheme
Scheme
(import (scheme base) (scheme inexact) (scheme read) (scheme write) (srfi 13)) ;; for string-length and string-ref   (define *string-fractions* ; string input of fractions "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1")   (define *fractions* ; create vector of fractions from string input (list->vector ; convert result to a vector, for constant access times (read (open-input-string ; read from the string of fractions, as a list (string-append "(" *string-fractions* ")")))))   ;; run a fractran interpreter, returning the next number for n ;; or #f if no next number available ;; assume fractions: ordered vector of positive fractions ;; n: a positive integer (define (fractran fractions n) (let ((max-n (vector-length fractions))) (let loop ((i 0)) (cond ((= i max-n) #f) ((integer? (* n (vector-ref fractions i))) (* n (vector-ref fractions i))) (else (loop (+ 1 i)))))))   ;; Task (define (display-result max-n) (do ((i 0 (+ 1 i)) (n 2 (fractran *fractions* n))) ((= i max-n) (newline)) (display n) (display " ")))   (display "Task: ") (display-result 20) ; show first 20 numbers   ;; Extra Credit: derive first 20 prime numbers (define (generate-primes target-number initial-n) (define (is-power-of-two? n) ; a binary with only 1 "1" bit is a power of 2 (cond ((<= n 2) ; exclude 2 and 1 #f) (else (let loop ((i 0) (acc 0) (binary-str (number->string n 2))) (cond ((= i (string-length binary-str)) #t) ((and (eq? (string-ref binary-str i) #\1) (= 1 acc)) #f) ((eq? (string-ref binary-str i) #\1) (loop (+ 1 i) (+ 1 acc) binary-str)) (else (loop (+ 1 i) acc binary-str))))))) (define (extract-prime n) ; just gets the number of zeroes in binary (let ((binary-str (number->string n 2))) (- (string-length binary-str) 1))) ; (let loop ((count 0) (n initial-n)) (when (< count target-number) (cond ((eq? n #f) (display "-- FAILED TO COMPUTE N --\n")) ((is-power-of-two? n) (display (extract-prime n)) (display " ") (loop (+ 1 count) (fractran *fractions* n))) (else (loop count (fractran *fractions* n)))))) (newline))   (display "Primes:\n") (generate-primes 20 2) ; create first 20 primes
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#ColdFusion
ColdFusion
<cffunction name="multiply" returntype="numeric"> <cfargument name="a" type="numeric"> <cfargument name="b" type="numeric"> <cfreturn a * b> </cffunction>
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Ring
Ring
  decimals(3) gamma = 0.577 coeff = -0.655 quad = -0.042 qui = 0.166 set = -0.042   for i=1 to 10 see gammafunc(i / 3.0) + nl next   func recigamma z return z + gamma * pow(z,2) + coeff * pow(z,3) + quad * pow(z,4) + qui * pow(z,5) + set * pow(z,6)   func gammafunc z if z = 1 return 1 but fabs(z) <= 0.5 return 1 / recigamma(z) else return (z - 1) * gammafunc(z-1) ok  
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#RLaB
RLaB
$a = [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_20253_88108, -0.04200_26350_34095_23553, 0.16653_86113_82291_48950, -0.04219_77345_55544_33675, -0.00962_19715_27876_97356, 0.00721_89432_46663_09954, -0.00116_51675_91859_06511, -0.00021_52416_74114_95097, 0.00012_80502_82388_11619, -0.00002_01348_54780_78824, -0.00000_12504_93482_14267, 0.00000_11330_27231_98170, -0.00000_02056_33841_69776, 0.00000_00061_16095_10448, 0.00000_00050_02007_64447, -0.00000_00011_81274_57049, 0.00000_00001_04342_67117, 0.00000_00000_07782_26344, -0.00000_00000_03696_80562, 0.00000_00000_00510_03703, -0.00000_00000_00020_58326, -0.00000_00000_00005_34812, 0.00000_00000_00001_22678, -0.00000_00000_00000_11813, 0.00000_00000_00000_00119, 0.00000_00000_00000_00141, -0.00000_00000_00000_00023, 0.00000_00000_00000_00002 ]   def gamma(x) y = Float(x) - 1 1.0 / $a.reverse.inject {|sum, an| sum * y + an} end   (1..10).each {|i| puts format("%.14e", gamma(i/3.0))}
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#VBScript
VBScript
Function ASCII_Sequence(range) arr = Split(range,"..") For i = Asc(arr(0)) To Asc(arr(1)) ASCII_Sequence = ASCII_Sequence & Chr(i) & " " Next End Function   WScript.StdOut.Write ASCII_Sequence(WScript.Arguments(0)) WScript.StdOut.WriteLine
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Verilog
Verilog
module main; integer i;   initial begin for(i = 97; i <= 122; i=i+1) begin $write("%c ",i); end $finish ; end endmodule  
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
#Python
Python
print "Hello world!"
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#PowerShell
PowerShell
  function g ($x) { $x + $x } function f ($x) { $x*$x*$x } f (g 1)  
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Prolog
Prolog
:- use_module(lambda).   compose(F,G, FG) :- FG = \X^Z^(call(G,X,Y), call(F,Y,Z)).  
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Tcl
Tcl
package require Tk   set SIZE 800 set SCALE 4.0 set BRANCHES 14 set ROTATION_SCALE 0.85 set INITIAL_LENGTH 50.0   proc draw_tree {w x y dx dy size theta depth} { global SCALE ROTATION_SCALE $w create line $x $y [expr {$x + $dx*$size}] [expr {$y + $dy*$size}] if {[incr depth -1] >= 0} { set x [expr {$x + $dx*$size}] set y [expr {$y + $dy*$size}] set ntheta [expr {$theta * $ROTATION_SCALE}]   # Draw left branch draw_tree $w $x $y \ [expr {$dx*cos($theta) + $dy*sin($theta)}] \ [expr {$dy*cos($theta) - $dx*sin($theta)}] \ [expr {$size * (rand() + $SCALE - 1) / $SCALE}] $ntheta $depth # Draw right branch draw_tree $w $x $y \ [expr {$dx*cos(-$theta) + $dy*sin(-$theta)}] \ [expr {$dy*cos(-$theta) - $dx*sin(-$theta)}] \ [expr {$size * (rand() + $SCALE - 1) / $SCALE}] $ntheta $depth } }   pack [canvas .c -width $SIZE -height $SIZE] draw_tree .c [expr {$SIZE/2}] [expr {$SIZE-10}] 0.0 -1.0 $INITIAL_LENGTH \ [expr {3.1415927 / 8}] $BRANCHES
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "rational.s7i";   const func array integer: fractran (in integer: limit, in var integer: number, in array rational: program) is func result var array integer: output is 0 times 0; local var integer: index is 1; var rational: newNumber is 0/1; begin output := [] (number); while index <= length(program) and length(output) <= limit do newNumber := rat(number) * program[index]; if newNumber = rat(trunc(newNumber)) then number := trunc(newNumber); output &:= number; index := 1; else incr(index); end if; end while; end func;   const proc: main is func local const array rational: program is [] (17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1); var array integer: output is 0 times 0; var integer: number is 0; begin output := fractran(15, 2, program); for number range output do write(number <& " "); end for; writeln; end func;
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Common_Lisp
Common Lisp
(defun multiply (a b) (* a b))   (multiply 2 3)
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Ruby
Ruby
$a = [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_20253_88108, -0.04200_26350_34095_23553, 0.16653_86113_82291_48950, -0.04219_77345_55544_33675, -0.00962_19715_27876_97356, 0.00721_89432_46663_09954, -0.00116_51675_91859_06511, -0.00021_52416_74114_95097, 0.00012_80502_82388_11619, -0.00002_01348_54780_78824, -0.00000_12504_93482_14267, 0.00000_11330_27231_98170, -0.00000_02056_33841_69776, 0.00000_00061_16095_10448, 0.00000_00050_02007_64447, -0.00000_00011_81274_57049, 0.00000_00001_04342_67117, 0.00000_00000_07782_26344, -0.00000_00000_03696_80562, 0.00000_00000_00510_03703, -0.00000_00000_00020_58326, -0.00000_00000_00005_34812, 0.00000_00000_00001_22678, -0.00000_00000_00000_11813, 0.00000_00000_00000_00119, 0.00000_00000_00000_00141, -0.00000_00000_00000_00023, 0.00000_00000_00000_00002 ]   def gamma(x) y = Float(x) - 1 1.0 / $a.reverse.inject {|sum, an| sum * y + an} end   (1..10).each {|i| puts format("%.14e", gamma(i/3.0))}
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Vim_Script
Vim Script
let lower = [] for c in range(0, 25) let lower += [nr2char(c + char2nr("a"))] endfor
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Visual_Basic
Visual Basic
Module LowerASCII   Sub Main() Dim alphabets As New List(Of Char) For i As Integer = Asc("a") To Asc("z") alphabets.Add(Chr(i)) Next Console.WriteLine(String.Join("", alphabets.ToArray)) End Sub   End Module  
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
#QB64
QB64
PRINT "Hello world!"
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#PureBasic
PureBasic
;Declare how our function looks like Prototype.i Func(Arg.i)   ; Make a procedure that composes any functions of type "Func" Procedure Compose(*a.Func,*b.Func, x) ProcedureReturn *a(*b(x)) EndProcedure   ; Just a procedure fitting "Func" Procedure f(n) ProcedureReturn 2*n EndProcedure   ; Yet another procedure fitting "Func" Procedure g(n) ProcedureReturn n+1 EndProcedure   ;- Test it X=Random(100) Title$="With x="+Str(x) Body$="Compose(f(),g(), x) ="+Str(Compose(@f(),@g(),X)) MessageRequester(Title$,Body$)
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Purity
Purity
  data compose = f => g => $f . $g  
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT dest="fracaltree.svg" ERROR/STOP CREATE (dest,fdf-o,-std-) ACCESS d: WRITE/ERASE/RECORDS/UTF8 $dest s,text MODE DATA $$ header=* <?xml version="1.0" standalone="yes"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="320"> <style type="text/css"><![CDATA[ line { stroke: brown; stroke-width: .05; } ]]></style> $$ WRITE/NEXT d header $$ defsbeg=* <defs> <g id="stem"> <line x1="0" y1="0" x2="0" y2="-1"/> </g> <g id="l"><use xlink:href="#stem"/></g> $$ WRITE/NEXT d defsbeg $$ LOOP n=10,21 $$ id=n+1,lastnr=VALUE(n) $$ g=* <g id="{id}"> <use xlink:href="#{n}" transform="translate(0, -1) rotate(-35) scale(.7)"/> <use xlink:href="#{n}" transform="translate(0, -1) rotate(+35) scale(.7)"/> <use xlink:href="#stem"/></g> $$ WRITE/NEXT d g $$ ENDLOOP $$ defsend = * </defs> <g transform="translate(200, 320) scale(100)"> <use xlink:href="#{lastnr}"/> </g> $$ MODE TUSCRIPT WRITE/NEXT d defsend WRITE/NEXT d "</svg>" ENDACCESS d  
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#TypeScript
TypeScript
// Set up canvas for drawing var canvas: HTMLCanvasElement = document.createElement('canvas') canvas.width = 600 canvas.height = 500 document.body.appendChild(canvas) var ctx: CanvasRenderingContext2D = canvas.getContext('2d') ctx.fillStyle = '#000' ctx.lineWidth = 1   // constants const degToRad: number = Math.PI / 180.0 const totalDepth: number = 9   /** Helper function that draws a line on the canvas */ function drawLine(x1: number, y1: number, x2: number, y2: number): void { ctx.moveTo(x1, y1) ctx.lineTo(x2, y2) }   /** Draws a branch at the given point and angle and then calls itself twice */ function drawTree(x1: number, y1: number, angle: number, depth: number): void { if (depth !== 0) { let x2: number = x1 + (Math.cos(angle * degToRad) * depth * 10.0) let y2: number = y1 + (Math.sin(angle * degToRad) * depth * 10.0) drawLine(x1, y1, x2, y2) drawTree(x2, y2, angle - 20, depth - 1) drawTree(x2, y2, angle + 20, depth - 1) } }   // actual drawing of tree ctx.beginPath() drawTree(300, 500, -90, totalDepth) ctx.closePath() ctx.stroke()    
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Sidef
Sidef
var str ="17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1" const FractalProgram = str.split(',').map{.num} #=> array of rationals   func runner(n, callback) { var num = 2 n.times { callback(num *= FractalProgram.find { |f| f * num -> is_int }) } }   func prime_generator(n, callback) { var x = 0; runner(Inf, { |num| var l = num.log2 if (l.floor == l) { callback(l.int) ++x == n && return nil } }) }   STDOUT.autoflush(true)   runner(20, {|n| print (n, ' ') }) print "\n"   prime_generator(20, {|n| print (n, ' ') }) print "\n"
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Cowgol
Cowgol
sub multiply(a: int32, b: int32): (rslt: int32) is rslt := a * b; end sub
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Scala
Scala
import java.util.Locale._   object Gamma { def stGamma(x:Double):Double=math.sqrt(2*math.Pi/x)*math.pow((x/math.E), x)   def laGamma(x:Double):Double={ val p=Seq(676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7)   if(x < 0.5) { math.Pi/(math.sin(math.Pi*x)*laGamma(1-x)) } else { val x2=x-1 val t=x2+7+0.5 val a=p.zipWithIndex.foldLeft(0.99999999999980993)((r,v) => r+v._1/(x2+v._2+1)) math.sqrt(2*math.Pi)*math.pow(t, x2+0.5)*math.exp(-t)*a } }   def main(args: Array[String]): Unit = { println("Gamma Stirling Lanczos") for(x <- 0.1 to 2.0 by 0.1) println("%.1f ->  %.16f  %.16f".formatLocal(ENGLISH, x, stGamma(x), laGamma(x))) } }
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Visual_Basic_.NET
Visual Basic .NET
Module LowerASCII   Sub Main() Dim alphabets As New List(Of Char) For i As Integer = Asc("a") To Asc("z") alphabets.Add(Chr(i)) Next Console.WriteLine(String.Join("", alphabets.ToArray)) End Sub   End Module  
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Vlang
Vlang
fn loweralpha() string { mut p := []u8{len: 26} for i in 97..123 { p[i-97] = u8(i) } return p.bytestr() }
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
#Quackery
Quackery
say "Hello world!"
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Python
Python
compose = lambda f, g: lambda x: f( g(x) )
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Qi
Qi
  (define compose F G -> (/. X (F (G X))))   ((compose (+ 1) (+ 2)) 3) \ (Outputs 6) \  
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "math" for Math   var Radians = Fn.new { |d| d * Num.pi / 180 }   class FractalTree { construct new(width, height) { Window.title = "Fractal Tree" Window.resize(width, height) Canvas.resize(width, height) _fore = Color.white }   init() { drawTree(400, 500, -90, 9) }   drawTree(x1, y1, angle, depth) { if (depth == 0) return var r = Radians.call(angle) var x2 = x1 + (Math.cos(r) * depth * 10).truncate var y2 = y1 + (Math.sin(r) * depth * 10).truncate Canvas.line(x1, y1, x2, y2, _fore) drawTree(x2, y2, angle - 20, depth - 1) drawTree(x2, y2, angle + 20, depth - 1) }   update() {}   draw(alpha) {} }   var Game = FractalTree.new(800, 600)
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Tcl
Tcl
package require Tcl 8.6   oo::class create Fractran { variable fracs nco constructor {fractions} { set fracs {} foreach frac $fractions { if {[regexp {^(\d+)/(\d+),?$} $frac -> num denom]} { lappend fracs $num $denom } else { return -code error "$frac is not a supported fraction" } } if {![llength $fracs]} { return -code error "need at least one fraction" } }   method execute {n {steps 15}} { set co [coroutine [incr nco] my Generate $n] for {set i 0} {$i < $steps} {incr i} { lappend result [$co] } catch {rename $co ""} return $result }   method Step {n} { foreach {num den} $fracs { if {$n % $den} continue return [expr {$n * $num / $den}] } return -code break } method Generate {n} { yield [info coroutine] while 1 { yield $n set n [my Step $n] } return -code break } }   set ft [Fractran new { 17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1 }] puts [$ft execute 2]
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Creative_Basic
Creative Basic
  DECLARE Multiply(N1:INT,N2:INT)   DEF A,B:INT   A=2:B=2   OPENCONSOLE   PRINT Multiply(A,B)   PRINT:PRINT"Press any key to close."   DO:UNTIL INKEY$<>""   CLOSECONSOLE   END   SUB Multiply(N1:INT,N2:INT)   DEF Product:INT   Product=N1*N2   RETURN Product   'Can also be written with no code in the subroutine and just RETURN N1*N2.  
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Scheme
Scheme
  (import (scheme base) (scheme inexact) (scheme write))   (define PI 3.14159265358979323846264338327950) (define e 2.7182818284590452353602875)   (define gamma-lanczos (let ((p '(676.5203681218851 -1259.1392167224028 771.32342877765313 -176.61502916214059 12.507343278686905 -0.13857109526572012 9.9843695780195716e-6 1.5056327351493116e-7))) (lambda (x) (if (< x 0.5) (/ PI (* (sin (* PI x)) (gamma-lanczos (- 1 x)))) (let* ((x2 (- x 1)) (t (+ x2 7 0.5)) (a (do ((ps p (cdr ps)) (idx 0 (+ 1 idx)) (res 0.99999999999980993 (+ res (/ (car ps) (+ x2 idx 1))))) ((null? ps) res)))) (* (sqrt (* 2 PI)) (expt t (+ x2 0.5)) (exp (- t)) a))))))   (define (gamma-stirling x) (* (sqrt (* 2 (/ PI x))) (expt (/ x e) x)))   (define gamma-taylor (let ((a (reverse '(1.00000000000000000000 0.57721566490153286061 -0.65587807152025388108 -0.04200263503409523553 0.16653861138229148950 -0.04219773455554433675 -0.00962197152787697356 0.00721894324666309954 -0.00116516759185906511 -0.00021524167411495097 0.00012805028238811619 -0.00002013485478078824 -0.00000125049348214267 0.00000113302723198170 -0.00000020563384169776 0.00000000611609510448 0.00000000500200764447 -0.00000000118127457049 0.00000000010434267117 0.00000000000778226344 -0.00000000000369680562 0.00000000000051003703 -0.00000000000002058326 -0.00000000000000534812 0.00000000000000122678 -0.00000000000000011813 0.00000000000000000119 0.00000000000000000141 -0.00000000000000000023 0.00000000000000000002)))) (lambda (x) (let ((y (- x 1))) (do ((as a (cdr as)) (res 0 (+ (car as) (* res y)))) ((null? as) (/ 1 res)))))))   (do ((i 0.1 (+ i 0.1))) ((> i 2.01) ) (display (string-append "Gamma (" (number->string i) "): " "\n --- Lanczos : " (number->string (gamma-lanczos i)) "\n --- Stirling: " (number->string (gamma-stirling i)) "\n --- Taylor  : " (number->string (gamma-taylor i)) "\n")))  
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#WebAssembly
WebAssembly
(module $lowercase   (import "wasi_unstable" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)) )   (memory 1) (export "memory" (memory 0))   (func $main (export "_start") (local $i i32)   (i32.store (i32.const 0) (i32.const 8))  ;; offset to start of string (i32.store (i32.const 4) (i32.const 27))  ;; string length   (set_local $i (i32.const 0)) (loop  ;; mem[i+8] = i+97 (i32.store (i32.add (get_local $i) (i32.const 8)) (i32.add (get_local $i) (i32.const 97)))  ;; i = i+1 (set_local $i (i32.add (get_local $i) (i32.const 1)))  ;; if i < 26 then loop (br_if 0 (i32.lt_s (get_local $i) (i32.const 26))) )  ;; append a newline (i32.store (i32.add (get_local $i) (i32.const 8)) (i32.const 10))    ;; write to stdout (call $fd_write (i32.const 1)  ;; output stream to write to (1 == stdout) (i32.const 0)  ;; memory location containing string offset and length (i32.const 1)  ;; number of strings to write (i32.const 40) ;; location in memory to write number of bytes written ) drop ) )
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Wren
Wren
var alpha = [] for (c in 97..122) alpha.add(String.fromByte(c)) System.print(alpha.join())
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
#Quill
Quill
"Hello world!" print
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Quackery
Quackery
[ nested swap nested swap join ] is compose ( g f --> [ )   ( ----- demonstration ----- )   ( create a named nest -- equivalent to a function )   [ 2 * ] is double ( n --> n )   ( "[ 4 + ]" is an unnamed nest -- equivalent to a lambda function. )   ( "quoting" a nest with ' puts it on the stack rather than it being evaluated. "do" evaluates the top of stack. )   19 ' double ' [ 4 + ] compose do echo  
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#R
R
compose <- function(f,g) function(x) { f(g(x)) } r <- compose(sin, cos) print(r(.5))
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#XPL0
XPL0
include c:\cxpl\codes;   proc DrawBranch(Lev, Dir, Len, X, Y); int Lev; real Dir, Len; int X, Y; int Red, Grn; [Move(X, Y); X:= X + fix(Len*Cos(Dir)); Y:= Y + fix(Len*Sin(Dir)); Red:= 255-Lev*8; Grn:= Lev*12+100; Line(X, Y, Red<<16+Grn<<8); if Lev < 12 then \limit level of recursion [DrawBranch(Lev+1, Dir-0.4, Len*0.8, X, Y); \left DrawBranch(Lev+1, Dir+0.1, Len*0.8, X, Y); \right ]; ];   [SetVid($112); \set 640x480x24 video graphics mode DrawBranch(0, -3.14159/2.0, 80.0, 360, 460); if ChIn(1) then []; \wait for keystroke SetVid(3); \restore normal text mode ]
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#zkl
zkl
fcn fractalTree(){ scale:=0.76; sizeX:=400; sizeY:=300; bitmap:=PPM(sizeX*2,sizeY*2,0xFF|FF|FF); branch:='wrap(x1,y1,size,angle,depth){ ar:=angle.toRad(); x2:=x1 - size*ar.cos(); y2:=y1 + size*ar.sin(); color:=(0xff-depth*8).shiftLeft(16) + (depth*12+100).shiftLeft(8); bitmap.line(x1,y1, x2,y2, color); if(depth){ self.fcn(x2,y2,scale*size,angle - 30,depth - 1,vm.pasteArgs(5)); self.fcn(x2,y2,scale*size,angle + 8, depth - 1,vm.pasteArgs(5)); } }; branch(sizeX,0,sizeY/2,90.0,10); bitmap.write(File("foo.ppm","wb")); }();
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#TI-83_BASIC
TI-83 BASIC
100->T 2->N {17,78,19,23,29,77,95,77, 1,11,13,15,15,55}->LA {91,85,51,38,33,29,23,19,17,13,11,14, 2, 1}->LB Dim(LA)->U T->Dim(LC) For(I,1,T) 1->J: 1->F While J<=U and F=1 If remainder(N,LB(J))=0 Then Disp N N->LC(I) iPart(N/LB(J))*LA(J)->N 0->F End J+1->J End End
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#D
D
// A function: int multiply1(int a, int b) { return a * b; }   // Functions like "multiply1" can be evaluated at compile time if // they are called where a compile-time constant result is asked for: enum result = multiply1(2, 3); // Evaluated at compile time. int[multiply1(2, 4)] array; // Evaluated at compile time.   // A templated function: T multiply2(T)(T a, T b) { return a * b; }   // Compile-time multiplication can also be done using templates: enum multiply3(int a, int b) = a * b;   pragma(msg, multiply3!(2, 3)); // Prints "6" during compilation.   void main() { import std.stdio; writeln("2 * 3 = ", result); }
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Scilab
Scilab
function x=gammal(z) // Lanczos' lz=[ 1.000000000190015 .. 76.18009172947146 -86.50532032941677 24.01409824083091 .. -1.231739572450155 1.208650973866179e-3 -5.395239384953129e-6 ] if z < 0.5 then x=%pi/sin(%pi*z)-gammal(1-z) else z=z-1.0 b=z+5.5 a=lz(1) for i=1:6 a=a+(lz(i+1)/(z+i)) end x=exp((log(sqrt(2*%pi))+log(a)-b)+log(b)*(z+0.5)) end endfunction   printf("%4s %-9s %-9s\n","x","gamma(x)","gammal(x)") for i=1:30 x=i/10 printf("%4.1f %9f %9f\n",x,gamma(x),gammal(x)) end
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#xEec
xEec
h$` h$` >0_0 t h$y ms p h? jn00_0 p r h#1 ma t jn0_0 >00_0 p p r p
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#XLISP
XLISP
(defun ascii-lower () (defun add-chars (x y s) (if (<= x y) (add-chars (+ x 1) y (string-append s (string (integer->char x)))) s)) (add-chars 97 122 ""))
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
#Quite_BASIC
Quite BASIC
10 print "Hello world!"
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Racket
Racket
  (define (compose f g) (lambda (x) (f (g x))))  
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Raku
Raku
sub triple($n) { 3 * $n } my &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 }; say &f(5); # prints "-21".
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET level=12: LET LONG=45 20 LET x=127: LET y=0 30 LET rotation=PI/2 40 LET a1=PI/9: LET a2=PI/9 50 LET c1=0.75: LET c2=0.75 60 DIM x(level): DIM y(level) 70 BORDER 0: PAPER 0: INK 4: CLS 80 GO SUB 100 90 STOP 100 REM Tree 110 LET x(level)=x: LET y(level)=y 120 GO SUB 1000 130 IF level=1 THEN GO TO 240 140 LET level=level-1 150 LET LONG=LONG*c1 160 LET rotation=rotation-a1 170 GO SUB 100 180 LET LONG=LONG/c1*c2 190 LET rotation=rotation+a1+a2 200 GO SUB 100 210 LET rotation=rotation-a2 220 LET LONG=LONG/c2 230 LET level=level+1 240 LET x=x(level): LET y=y(level) 250 RETURN 1000 REM Draw 1010 LET yn=-SIN rotation*LONG+y 1020 LET xn=COS rotation*LONG+x 1030 PLOT x,y: DRAW xn-x,y-yn 1040 LET x=xn: LET y=yn 1050 RETURN
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#VBA
VBA
Option Base 1 Public prime As Variant Public nf As New Collection Public df As New Collection Const halt = 20 Private Sub init() prime = [{2,3,5,7,11,13,17,19,23,29,31}] End Sub Private Function factor(f As Long) As Variant Dim result(10) As Integer Dim i As Integer: i = 1 Do While f > 1 Do While f Mod prime(i) = 0 f = f \ prime(i) result(i) = result(i) + 1 Loop i = i + 1 Loop factor = result End Function Private Function decrement(ByVal a As Variant, b As Variant) As Variant For i = LBound(a) To UBound(a) a(i) = a(i) - b(i) Next i decrement = a End Function Private Function increment(ByVal a As Variant, b As Variant) As Variant For i = LBound(a) To UBound(a) a(i) = a(i) + b(i) Next i increment = a End Function Private Function test(a As Variant, b As Variant) flag = True For i = LBound(a) To UBound(a) If a(i) < b(i) Then flag = False Exit For End If Next i test = flag End Function Private Function unfactor(x As Variant) As Long result = 1 For i = LBound(x) To UBound(x) result = result * prime(i) ^ x(i) Next i unfactor = result End Function Private Sub compile(program As String) program = Replace(program, " ", "") programlist = Split(program, ",") For Each instruction In programlist parts = Split(instruction, "/") nf.Add factor(Val(parts(0))) df.Add factor(Val(parts(1))) Next instruction End Sub Private Function run(x As Long) As Variant n = factor(x) counter = 0 Do While True For i = 1 To df.Count If test(n, df(i)) Then n = increment(decrement(n, df(i)), nf(i)) Exit For End If Next i Debug.Print unfactor(n); counter = counter + 1 If num = 31 Or counter >= halt Then Exit Do Loop Debug.Print run = n End Function Private Function steps(x As Variant) As Variant 'expects x=factor(n) For i = 1 To df.Count If test(x, df(i)) Then x = increment(decrement(x, df(i)), nf(i)) Exit For End If Next i steps = x End Function Private Function is_power_of_2(x As Variant) As Boolean flag = True For i = LBound(x) + 1 To UBound(x) If x(i) > 0 Then flag = False Exit For End If Next i is_power_of_2 = flag End Function Private Function filter_primes(x As Long, max As Integer) As Long n = factor(x) i = 0: iterations = 0 Do While i < max If is_power_of_2(steps(n)) Then Debug.Print n(1); i = i + 1 End If iterations = iterations + 1 Loop Debug.Print filter_primes = iterations End Function Public Sub main() init compile ("17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1") Debug.Print "First 20 results:" output = run(2) Debug.Print "First 30 primes:" Debug.Print "after"; filter_primes(2, 30); "iterations." End Sub
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Dart
Dart
main(){ print(multiply(1,2)); print(multiply2(1,2)); print(multiply3(1,2)); }   // the following definitions are equivalent // arrow syntax without type annotations multiply(num1, num2) => num1 * num2;   // arrow syntax with type annotations int multiply2(int num1, int num2) => num1 * num2;   // c style with curly braces int multiply3(int num1, int num2){ return num1 * num2; }  
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const func float: gamma (in float: X) is func result var float: result is 0.0; local const array float: A is [] ( 1.00000000000000000000, 0.57721566490153286061, -0.65587807152025388108, -0.04200263503409523553, 0.16653861138229148950, -0.04219773455554433675, -0.00962197152787697356, 0.00721894324666309954, -0.00116516759185906511, -0.00021524167411495097, 0.00012805028238811619, -0.00002013485478078824, -0.00000125049348214267, 0.00000113302723198170, -0.00000020563384169776, 0.00000000611609510448, 0.00000000500200764447, -0.00000000118127457049, 0.00000000010434267117, 0.00000000000778226344, -0.00000000000369680562, 0.00000000000051003703, -0.00000000000002058326, -0.00000000000000534812, 0.00000000000000122678, -0.00000000000000011813, 0.00000000000000000119, 0.00000000000000000141, -0.00000000000000000023, 0.00000000000000000002); var float: Y is 0.0; var float: Sum is A[maxIdx(A)]; var integer: N is 0; begin Y := X - 1.0; for N range pred(maxIdx(A)) downto minIdx(A) do Sum := Sum * Y + A[N]; end for; result := 1.0 / Sum; end func;   const proc: main is func local var integer: I is 0; begin for I range 1 to 10 do writeln((gamma(flt(I) / 3.0)) digits 15); end for; end func;
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Sidef
Sidef
var a = [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_20253_88108, -0.04200_26350_34095_23553, 0.16653_86113_82291_48950, -0.04219_77345_55544_33675, -0.00962_19715_27876_97356, 0.00721_89432_46663_09954, -0.00116_51675_91859_06511, -0.00021_52416_74114_95097, 0.00012_80502_82388_11619, -0.00002_01348_54780_78824, -0.00000_12504_93482_14267, 0.00000_11330_27231_98170, -0.00000_02056_33841_69776, 0.00000_00061_16095_10448, 0.00000_00050_02007_64447, -0.00000_00011_81274_57049, 0.00000_00001_04342_67117, 0.00000_00000_07782_26344, -0.00000_00000_03696_80562, 0.00000_00000_00510_03703, -0.00000_00000_00020_58326, -0.00000_00000_00005_34812, 0.00000_00000_00001_22678, -0.00000_00000_00000_11813, 0.00000_00000_00000_00119, 0.00000_00000_00000_00141, -0.00000_00000_00000_00023, 0.00000_00000_00000_00002 ]   func gamma(x) { var y = (x - 1) 1 / a.reverse.reduce {|sum, an| sum*y + an} }   for i in 1..10 { say ("%.14e" % gamma(i/3)) }
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#XPL0
XPL0
char I, A(26); for I:= 0 to 26-1 do A(I):= I+^a