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/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Prolog
Prolog
:- use_module(library(lambda)).     compose(F,G, FG) :- FG = \X^Z^(call(G,X,Y), call(F,Y,Z)).   cube(X, Y) :- Y is X ** 3.   cube_root(X, Y) :- Y is X ** (1/3).   first_class :- L = [sin, cos, cube], IL = [asin, acos, cube_root],   % we create the composed functions maplist(compose, L, IL, Lst),   % we call th...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Lambdatalk
Lambdatalk
  1) Let's create this function   {def A.flatten {def A.flatten.r {lambda {:a} {if {A.empty? :a} then else {let { {:b {A.first :a}} } {if {A.array? :b} then {A.flatten.r :b} else :b} } {A.flatten.r {A.rest :a}} }}} {lambda {:a} {A.new {A.flatten...
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#Run_BASIC
Run BASIC
input "Number of rows: "; rows dim colSize(rows) for col=1 to rows colSize(col) = len(str$(col + rows * (rows-1)/2)) next   thisNum = 1 for r = 1 to rows for col = 1 to r print right$( " "+str$(thisNum), colSize(col)); " "; thisNum = thisNum + 1 next print next
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#Rust
Rust
fn main() { floyds_triangle(5); floyds_triangle(14); }   fn floyds_triangle(n: u32) { let mut triangle: Vec<Vec<String>> = Vec::new(); let mut current = 0; for i in 1..=n { let mut v = Vec::new(); for _ in 0..i { current += 1; v.push(current); } ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Maple
Maple
lst := ["ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"]: perm := table(): for letter in "ABCD" do perm[letter] := 0: end do: for item in lst do for letter in "ABCD" do perm[letter] += StringTools:-First...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ProvidedSet = {"ABCD" , "CABD" , "ACDB" , "DACB" , "BCDA" , "ACBD", "ADCB" , "CDAB", "DABC", "BCAD" , "CADB", "CDBA" , "CBAD" , "ABDC", "ADBC" , "BDCA", "DCBA" , "BACD", "BADC", "BDAC" , "CBDA", "DBCA", "DCAB"};   Complement[StringJoin /@ Permutations@Characters@First@#, #] &@ProvidedSet     ->{"DBAC"}
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#PHP
PHP
<?php // Created with PHP 7.0   function printLastSundayOfAllMonth($year) { $months = array( 'January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December');   foreach ($months as $month) { echo $month . ': ' . date('Y-m-d', strtotime('l...
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Befunge
Befunge
for i = 0; i <= 100; i++ out = "" if i % 3 == 0 out = "Fizz" end if i % 5 == 0 out = out + "Buzz" end if out == "" out = i end print(out) end
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Perl
Perl
#!/usr/bin/perl -w use DateTime ;   my @happymonths ; my @workhardyears ; my @longmonths = ( 1 , 3 , 5 , 7 , 8 , 10 , 12 ) ; my @years = 1900..2100 ; foreach my $year ( @years ) { my $countmonths = 0 ; foreach my $month ( @longmonths ) { my $dt = DateTime->new( year => $year , month =...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Python
Python
>>> # Some built in functions and their inverses >>> from math import sin, cos, acos, asin >>> # Add a user defined function and its inverse >>> cube = lambda x: x * x * x >>> croot = lambda x: x ** (1/3.0) >>> # First class functions allow run-time creation of functions from functions >>> # return function compose(f,g...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Lasso
Lasso
local(original = json_deserialize('[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]'))   #original '<br />' (with item in delve(#original) select #item) -> asstaticarray
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#Scala
Scala
def floydstriangle( n:Int ) = { val s = (1 to n) val t = s map {i => (s.take(i-1).sum) + 1}   (s zip t) foreach { n => var m = n._2;   for( i <- 0 until n._1 ) { val w = (t.last + i).toString.length + 1 // Column width from last row print(" " + m takeRight w ) m+=1 }   ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#MATLAB
MATLAB
function perm = findMissingPerms(list)   permsList = perms(list(1,:)); %Generate all permutations of the 4 letters perm = []; %This is the functions return value if the list is not missing a permutation   %Normally the rest of this would be vectorized, but because this is %done on a vector of strings, t...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#PicoLisp
PicoLisp
(de lastSundays (Y) (for M 12 (prinl (dat$ (find '((D) (= "Sunday" (day D))) (mapcar '((D) (date Y M D)) `(range 31 22)) ) "-" ) ) ) )
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#PowerShell
PowerShell
  function last-dayofweek { param( [Int][ValidatePattern("[1-9][0-9][0-9][0-9]")]$year, [String][validateset('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')]$dayofweek ) $date = (Get-Date -Year $year -Month 1 -Day 1) while($date.DayOfWeek -ne $dayofweek) {$date = $date....
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#blz
blz
for i = 0; i <= 100; i++ out = "" if i % 3 == 0 out = "Fizz" end if i % 5 == 0 out = out + "Buzz" end if out == "" out = i end print(out) end
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Phix
Phix
with javascript_semantics sequence m31 = {"January",0,"March",0,"May",0,"July","August",0,"October",0,"December"} integer y,m, nmonths = 0 string months sequence res = {}, none = {} for y=1900 to 2100 do months = "" for m=1 to 12 do if string(m31[m]) and day_of_week(y,m,1,tru...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#R
R
cube <- function(x) x^3 croot <- function(x) x^(1/3) compose <- function(f, g) function(x){f(g(x))}   f1 <- c(sin, cos, cube) f2 <- c(asin, acos, croot)   for(i in 1:3) { print(compose(f1[[i]], f2[[i]])(.5)) }
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Racket
Racket
#lang racket   (define (compose f g) (λ (x) (f (g x)))) (define (cube x) (expt x 3)) (define (cube-root x) (expt x (/ 1 3))) (define funlist (list sin cos cube)) (define ifunlist (list asin acos cube-root))   (for ([f funlist] [i ifunlist]) (displayln ((compose i f) 0.5)))
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#LFE
LFE
  > (: lists flatten '((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ())) (1 2 3 4 5 6 7 8)  
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: writeFloyd (in integer: rows) is func local var integer: number is 1; var integer: numBeforeLastLine is 0; var integer: line is 0; var integer: column is 0; begin numBeforeLastLine := rows * pred(rows) div 2; for line range 1 to rows do for colum...
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#Sidef
Sidef
func floyd(rows, n=1) { var max = Math.range_sum(1, rows) var widths = (max-rows .. max-1 -> map{.+n->to_s.len}) { |r| say %'#{1..r -> map{|i| "%#{widths[i-1]}d" % n++}.join(" ")}' } << 1..rows }   floyd(5) # or: floyd(5, 88) floyd(14) # or: floyd(14, 900)
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Nim
Nim
import strutils   proc missingPermutation(arr: openArray[string]): string = result = "" if arr.len == 0: return if arr.len == 1: return arr[0][1] & arr[0][0]   for pos in 0 ..< arr[0].len: var s: set[char] = {} for permutation in arr: let c = permutation[pos] if c in s: s.excl c else: ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#OCaml
OCaml
(* insert x at all positions into li and return the list of results *) let rec insert x = function | [] -> [[x]] | a::m as li -> (x::li) :: (List.map (fun y -> a::y) (insert x m))   (* list of all permutations of li *) let permutations li = List.fold_right (fun a z -> List.concat (List.map (insert a) z)) li [[]]...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#PureBasic
PureBasic
Procedure LastSundayOfEachMonth(yyyy.i,List lfem.i()) Define dv.i=ParseDate("%yyyy",Str(yyyy)), mv.i=1 NewList d.i() For d=1 To 365 dv=AddDate(dv,#PB_Date_Day,1) If DayOfWeek(dv)=0 AddElement(d()) : d()=dv EndIf Next dv=0 For mv=1 To 12 ForEach d() If dv<d() And Month(d())=...
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Boo
Boo
def fizzbuzz(size): for i in range(1, size): if i%15 == 0: print 'FizzBuzz' elif i%5 == 0: print 'Buzz' elif i%3 == 0: print 'Fizz' else: print i   fizzbuzz(101)
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Picat
Picat
go ?=> println("Months with five weekends:"), FiveWeekends = [ [Year,Month] : Year in 1900..2100, Month in [1,3,5,7,8,10,12], dow(Year,Month,1) == 5], WLen = FiveWeekends.len, println(take(FiveWeekends,5)), println("..."), println(drop(FiveWeekends,WLen-5)), println(len=WLen), nl,   println("Years w/o...
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#PicoLisp
PicoLisp
(setq Lst (make (for Y (range 1900 2100) (for M (range 1 12) (and (date Y M 31) (= "Friday" (day (date Y M 1))) (link (list (get *Mon M) Y)) ) ) ) ) )   (prinl "There are " (length Lst) " months with five weekends:") (mapc println (head 5 Lst)) ...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Raku
Raku
sub infix:<∘> (&𝑔, &𝑓) { -> \x { 𝑔 𝑓 x } }   my \𝐴 = &sin, &cos, { $_ ** <3/1> } my \𝐵 = &asin, &acos, { $_ ** <1/3> }   say .(.5) for 𝐴 Z∘ 𝐵
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#REBOL
REBOL
rebol [ Title: "First Class Functions" URL: http://rosettacode.org/wiki/First-class_functions ]   ; Functions "foo" and "bar" are used to prove that composition ; actually took place by attaching their signatures to the result.   foo: func [x][reform ["foo:" x]] bar: func [x][reform ["bar:" x]]   cube: func [x][x * ...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Logo
Logo
to flatten :l if not list? :l [output :l] if empty? :l [output []] output sentence flatten first :l flatten butfirst :l end   ; using a template iterator (map combining results into a sentence) to flatten :l output map.se [ifelse or not list? ? empty? ? [?] [flatten ?]] :l end   make "a [[1] 2 [[3 4] 5] [[[]]] ...
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#SPL
SPL
floyd(5) floyd(14)   floyd(n)= k = 0 > r, 1..n s = "" > j, 1..r k += 1 f = ">"+#.upper(#.log10((n-1)*n/2+j+1)+1)+">" s += #.str(k,f) < #.output(s) < .
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#Tcl
Tcl
proc floydTriangle n { # Compute the column widths for {set i [expr {$n*($n-1)/2+1}]} {$i <= $n*($n+1)/2} {incr i} { lappend w [string length $i] } # Print the triangle for {set i 0; set j 1} {$j <= $n} {incr j} { for {set p -1; set k 0} {$k < $j} {incr k} { puts -nonewline [format "%*d " [li...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Octave
Octave
given = [ 'ABCD';'CABD';'ACDB';'DACB'; ... 'BCDA';'ACBD';'ADCB';'CDAB'; ... 'DABC';'BCAD';'CADB';'CDBA'; ... 'CBAD';'ABDC';'ADBC';'BDCA'; ... 'DCBA';'BACD';'BADC';'BDAC'; ... 'CBDA';'DBCA';'DCAB' ]; val = 4.^(3:-1:0)'; there = 1+(toascii(given)-toascii('A'))*val; every ...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Python
Python
  import sys import calendar   year = 2013 if len(sys.argv) > 1: try: year = int(sys.argv[-1]) except ValueError: pass   for month in range(1, 13): last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month)) print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#QuickBASIC_4.5
QuickBASIC 4.5
  ' PROGRAM Last Sundays in Quick BASIC 4.5 (LASTSQB1) ' This program will calculate the last Sundays of each month in a given year. ' It works assigning the year in the command prompt ' Usage: LASTSQB1 Year ' In the IDE, be sure to assign the COMMAND$ value in the Run menu.   ' Var DIM iWY AS INTEGER DIM A AS STRING D...
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#BQN
BQN
(∾´∾⟜"Fizz"‿"Buzz"/˜·(¬∨´)⊸∾0=3‿5|⊢)¨1+↕100
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Pike
Pike
int(0..1) weekends(object day) { return (<5,6,7>)[day->week_day()]; }   int(0..1) has5(object month) { return sizeof(filter(month->days(), weekends))==15; }   object range = Calendar.Year(1900)->distance(Calendar.Year(2101)); array have5 = filter(range->mo...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#REXX
REXX
/*REXX program demonstrates first─class functions (as a list of the names of functions).*/ A = 'd2x square sin cos' /*a list of functions to demonstrate.*/ B = 'x2d sqrt Asin Acos' /*the inverse functions of above list. */ w=digits() ...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Logtalk
Logtalk
flatten(List, Flatted) :- flatten(List, [], Flatted).   flatten(Var, Tail, [Var| Tail]) :- var(Var), !. flatten([], Flatted, Flatted) :- !. flatten([Head| Tail], List, Flatted) :- !, flatten(Tail, List, Aux), flatten(Head, Aux, Flatted). flatten(Head, Tail, [Head| Tail]).
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#TXR
TXR
(defun flotri (n) (let* ((last (trunc (* n (+ n 1)) 2)) (colw (mapcar [chain tostring length] (range (- last n -1) last))) (x 0)) (each ((r (range* 0 n))) (each ((c (range 0 r))) (format t " ~*a" [colw c] (inc x))) (put-line))))   (defun usage (msg) (...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Oz
Oz
declare GivenPermutations = ["ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB"]   %% four distinct variables between "A" and "D": proc {Description Root} Root = {FD.list 4 &A#&D} {FD.disti...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Quackery
Quackery
[ over 3 < if [ 1 - ] dup 4 / over + over 100 / - swap 400 / + swap 1 - [ table 0 3 2 5 0 3 5 1 4 6 2 4 ] + + 7 mod ] is dayofweek ( day month year --> weekday )   [ dup 400 mod 0 = iff [ drop true ] done dup 100 mod 0 = iff [ drop false ] ...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#R
R
  last_sundays <- function(year) { for (month in 1:12) { if (month == 12) { date <- as.Date(paste0(year,"-",12,"-",31)) } else { date <- as.Date(paste0(year,"-",month+1,"-",1))-1 } while (weekdays(date) != "Sunday") { date <- date - 1 } print(date) } } last_sundays(2004)  
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Bracmat
Bracmat
0:?i&whl'(1+!i:<101:?i&out$(mod$(!i.3):0&(mod$(!i.5):0&FizzBuzz|Fizz)|mod$(!i.5):0&Buzz|!i))
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#PL.2FI
PL/I
  weekends: procedure options (main); /* 28/11/2011 */ declare tally fixed initial (0); declare (d, dend, dn) fixed (10); declare (date_start, date_end) picture '99999999'; declare Leap fixed (1);   date_start = '01011900'; do date_start = date_start to '01012100'; d = days(date_start, 'D...
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#PowerShell
PowerShell
$fiveWeekends = @() $yearsWithout = @() foreach ($y in 1900..2100) { $hasFiveWeekendMonth = $FALSE foreach ($m in @("01","03","05","07","08",10,12)) { if ((Get-Date "$y-$m-1").DayOfWeek -eq "Friday") { $fiveWeekends += "$y-$m" $hasFiveWeekendMonth = $TRUE } } if ($hasFiveWeekendMonth -eq $FA...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Ruby
Ruby
cube = proc{|x| x ** 3} croot = proc{|x| x ** (1.quo 3)} compose = proc {|f,g| proc {|x| f[g[x]]}} funclist = [Math.method(:sin), Math.method(:cos), cube] invlist = [Math.method(:asin), Math.method(:acos), croot]   puts funclist.zip(invlist).map {|f, invf| compose[invf, f][0.5]}
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Rust
Rust
#![feature(conservative_impl_trait)] fn main() { let cube = |x: f64| x.powi(3); let cube_root = |x: f64| x.powf(1.0 / 3.0);   let flist  : [&Fn(f64) -> f64; 3] = [&cube , &f64::sin , &f64::cos ]; let invlist: [&Fn(f64) -> f64; 3] = [&cube_root, &f64::asin, &f64::acos];   let result = flist....
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Lua
Lua
function flatten(list) if type(list) ~= "table" then return {list} end local flat_list = {} for _, elem in ipairs(list) do for _, val in ipairs(flatten(elem)) do flat_list[#flat_list + 1] = val end end return flat_list end   test_list = {{1}, 2, {{3,4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}   print(tab...
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#VBA
VBA
Option Explicit Dim o As String Sub floyd(L As Integer) Dim r, c, m, n As Integer n = L * (L - 1) / 2 m = 1 For r = 1 To L o = o & vbCrLf For c = 1 To r o = o & Space(Len(CStr(n + c)) - Len(CStr(m))) & m & " " m = m + 1 Next Next End Sub Sub triangle()...
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#VBScript
VBScript
  ' Read the number of rows to use.. intRows = WScript.StdIn.ReadLine   ' Get the first number of the final row so we can calculate widths... intLastRowStart = (intRows ^ 2 - intRows) \ 2 + 1   For i = 1 To intRows intLastRow = intLastRowStart For j = 1 To i k = k + 1 WScript.StdOut.Write Space(Len(intLastRow) - ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#PARI.2FGP
PARI/GP
v=["ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"]; v=apply(u->permtonum(apply(n->n-64,Vec(Vecsmall(u)))),v); t=numtoperm(4, binomial(4!,2)-sum(i=1,#v,v[i])); Strchr(apply(n->n+64,t))
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Racket
Racket
  #lang racket (require srfi/19 math)   (define (days-in-month m y) (define lengths #(0 31 #f 31 30 31 30 31 31 30 31 30 31)) (define d (vector-ref lengths m)) (or d (days-in-feb y)))   (define (leap-year? y) (and (divides? 4 y) (or (not (divides? 100 y)) (divides? 400 y))))   (define (days-in...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Raku
Raku
sub MAIN ($year = Date.today.year) { for 1..12 -> $month { my $month-end = Date.new($year, $month, Date.new($year,$month,1).days-in-month); say $month-end - $month-end.day-of-week % 7; } }
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Brainf.2A.2A.2A
Brainf***
1.to 100 { n | true? n % 15 == 0 { p "FizzBuzz" } { true? n % 3 == 0 { p "Fizz" } { true? n % 5 == 0 { p "Buzz" } { p n } } } }
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Prolog
Prolog
main() :- weekends(1900, 2100, FiveWeekendList, RemainderWeekendList),   length(FiveWeekendList, FiveLen), maplist(write, ["Total five weekend months:", FiveLen, '\n']),   slice(FiveWeekendList, 5, FirstFiveList), maplist(write, ["First five {year,month} pairs:", FirstFiveList, '\n']),   sli...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Scala
Scala
import math._   // functions as values val cube = (x: Double) => x * x * x val cuberoot = (x: Double) => pow(x, 1 / 3d)   // higher order function, as a method def compose[A,B,C](f: B => C, g: A => B) = (x: A) => f(g(x))   // partially applied functions in Lists val fun = List(sin _, cos _, cube) val inv = List(asin _,...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Maple
Maple
  L := [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]:   with(ListTools):   Flatten(L);  
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Text   Module Module1   Function MakeTriangle(rows As Integer) As String Dim maxValue As Integer = (rows * (rows + 1)) / 2 Dim digit = 0 Dim output As New StringBuilder   For row = 1 To rows For column = 0 To row - 1 Dim colMaxDigit = (maxVa...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Pascal
Pascal
program MissPerm; {$MODE DELPHI} //for result   const maxcol = 4; type tmissPerm = 1..23; tcol = 1..maxcol; tResString = String[maxcol]; const Given_Permutations : array [tmissPerm] of tResString = ('ABCD', 'CABD', 'ACDB', 'DACB', 'BCDA', 'ACBD', 'ADCB', 'CDAB', 'DABC', 'BCAD', 'CADB', 'CDBA', ...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#REBOL
REBOL
#!/usr/bin/env rebol   last-sundays-of-year: function [ "Return series of last sunday (date!) for each month of the year" year [integer!] "which year?" ][ d: to-date reduce [1 1 year] ; start with first day of year collect [ repeat month 12 [ d/month: month + 1 ...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#REXX
REXX
/*REXX program displays dates of last Sundays of each month for any year*/ parse arg yyyy do j=1 for 12 _ = lastDOW('Sunday', j, yyyy) say right(_,4)'-'right(j,2,0)"-"left(word(_,2),2) end /*j*/ exit /*stick ...
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Brat
Brat
1.to 100 { n | true? n % 15 == 0 { p "FizzBuzz" } { true? n % 3 == 0 { p "Fizz" } { true? n % 5 == 0 { p "Buzz" } { p n } } } }
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#PureBasic
PureBasic
Procedure DateG(year.w, month.b, day) ;Returns the number of days before or after the earliest reference date ;in PureBasic's Date Library (1 Jan 1970) based on an assumed Gregorian calendar calculation Protected days days = (year) * 365 + (month - 1) * 31 + day - 1 - 719527 ;DAYS_UNTIL_1970_01_01 = 719527 If...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Scheme
Scheme
(define (compose f g) (lambda (x) (f (g x)))) (define (cube x) (expt x 3)) (define (cube-root x) (expt x (/ 1 3)))   (define function (list sin cos cube)) (define inverse (list asin acos cube-root))   (define x 0.5) (define (go f g) (if (not (or (null? f) (null? g))) (begin (display ((compose (ca...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Flatten[{{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}]
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#Wren
Wren
import "/fmt" for Fmt   var floyd = Fn.new { |n| var k = 1 for (i in 1..n) { for (j in 1..i) { Fmt.write("$*d ", (j < 9) ? 2 : 3, k) k = k + 1 } System.print() } }   System.print("Floyd(5):") floyd.call(5) System.print("\nFloyd(14):") floyd.call(14)
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Perl
Perl
sub check_perm { my %hash; @hash{@_} = (); for my $s (@_) { exists $hash{$_} or return $_ for map substr($s,1) . substr($s,0,1), (1..length $s); } }   # Check and display @perms = qw(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Ring
Ring
  see "What year to calculate (yyyy) : " give year see "Last Sundays in " + year + " are on :" + nl month = list(12) mo = [4,0,0,3,5,1,3,6,2,4,0,2] mon = [31,28,31,30,31,30,31,31,30,31,30,31] if year < 2100 leap = year - 1900 else leap = year - 1904 ok m = ((year-1900)%7) + floor(leap/4) % 7 for n = 1 to 12 month[...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Ruby
Ruby
require 'date'   def last_sundays_of_year(year = Date.today.year) (1..12).map do |month| d = Date.new(year, month, -1) # -1 means "last". d - d.wday end end   puts last_sundays_of_year(2013)
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#BrightScript_.28for_Roku.29
BrightScript (for Roku)
FOR i = 1 TO 100 fz = i MOD 3 = 0 bz = i MOD 5 = 0 IF fz OR bz IF fz AND NOT bz: str = "Fizz" ELSEIF bz AND NOT fz: str = "Buzz" ELSE str = "FizzBuzz" END IF ELSE str = i.ToStr() END IF ? str END FOR
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Python
Python
from datetime import timedelta, date   DAY = timedelta(days=1) START, STOP = date(1900, 1, 1), date(2101, 1, 1) WEEKEND = {6, 5, 4} # Sunday is day 6 FMT = '%Y %m(%B)'   def fiveweekendspermonth(start=START, stop=STOP): 'Compute months with five weekends between dates'   when = start lastmonth =...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Sidef
Sidef
func compose(f,g) { func (*args) { f(g(args...)) } }   var cube = func(a) { a.pow(3) } var croot = func(a) { a.root(3) }   var flist1 = [Num.method(:sin), Num.method(:cos), cube] var flist2 = [Num.method(:asin), Num.method(:acos), croot]   for a,b (flist1 ~Z flist2) { say compose(a, b)(0.5) }
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Slate
Slate
m@(Method traits) ** n@(Method traits) "Answers a new Method whose effect is that of calling the first method on the results of the second method applied to whatever arguments are passed. This composition is associative, i.e. (a ** b) ** c = a ** (b ** c). When the second method, n, does not take a *rest option or the ...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Maxima
Maxima
flatten([[[1, 2, 3], 4, [5, [6, 7]], 8], [[9, 10], 11], 12]); /* [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] */
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Mercury
Mercury
:- module flatten_a_list. :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det.   :- implementation.   :- import_module list.   :- type tree(T) ---> leaf(T)  ; node(list(tree(T))).   :- func flatten(tree(T)) = list(T).   flatten(leaf(X)) = [X]. flatten(node(Xs)) = condense(map(flat...
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#XPL0
XPL0
include c:\cxpl\codes; \include 'code' declarations   func IntLen(N); \Return number of digits in a positive integer int N; int I; for I:= 1 to 20 do [N:= N/10; if N=0 then return I];   proc Floyd(N); \Display Floyd's triangle int N; int M, Row, Col; real F; [M:= (N-1+1)*(N-1)/2; \last ...
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#zkl
zkl
fcn lcNum(row){(row*(row+1)/2+1)} // lazy caterer's sequence fcn floydsTriangle(rows){ fmt:=[lcNum(rows-1)..lcNum(rows)-1].pump(String,fcn(n){ String("%",n.toString().len(),"d ")}); // eg "%2d %2d %3d %3d" foreach row in (rows){ ns:=[lcNum(row)..lcNum(row+1)-1].walk(); // eg L(4.5,6) fmt[0,ns.le...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Phix
Phix
with javascript_semantics constant perms = {"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"} -- 1: sum of letters sequence r = repeat(0,4) for i=1 ...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Run_BASIC
Run BASIC
input "What year to calculate (yyyy) : ";year print "Last Sundays in ";year;" are:" dim month(12) mo$ = "4 0 0 3 5 1 3 6 2 4 0 2" mon$ = "31 28 31 30 31 30 31 31 30 31 30 31"   if year < 2100 then leap = year - 1900 else leap = year - 1904 m = ((year-1900) mod 7) + int(leap/4) mod 7 for n = 1 to 12 month(n) = (val...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Rust
Rust
use std::env::args; use time::{Date, Duration};   fn main() { let year = args().nth(1).unwrap().parse::<i32>().unwrap(); (1..=12) .map(|month| Date::try_from_ymd(year + month / 12, ((month % 12) + 1) as u8, 1)) .filter_map(|date| date.ok()) .for_each(|date| { let days_back = ...
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#C
C
int i = 0 ; char B[88] ; while ( i++ < 100 ) !sprintf( B, "%s%s", i%3 ? "":"Fizz", i%5 ? "":"Buzz" ) ? sprintf( B, "%d", i ):0, printf( ", %s", B );
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Quackery
Quackery
[ over 3 < if [ 1 - ] dup 4 / over + over 100 / - swap 400 / + swap 1 - [ table 0 3 2 5 0 3 5 1 4 6 2 4 ] + + 7 mod ] is dayofweek ( day month year --> weekday )   [ 1 - [ table $ "January" $ "February" $ "March" $ "April" $ "M...
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#R
R
ms = as.Date(sapply(c(1, 3, 5, 7, 8, 10, 12), function(month) paste(1900:2100, month, 1, sep = "-"))) ms = format(sort(ms[weekdays(ms) == "Friday"]), "%b %Y") message("There are ", length(ms), " months with five weekends.") message("The first five: ", paste(ms[1:5], collapse = ", ")) message("The last five: ", past...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Smalltalk
Smalltalk
|forward reverse composer compounds| "commodities" Number extend [ cube [ ^self raisedTo: 3 ] ]. Number extend [ cubeRoot [ ^self raisedTo: (1 / 3) ] ].   forward := #( #cos #sin #cube ). reverse := #( #arcCos #arcSin #cubeRoot ).   composer := [ :f :g | [ :x | f value: (g value: x) ] ].   "let us create composed...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#min
min
( =a (a 'quotation? any?) (a => #a) while a ) :deep-flatten   ((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()) deep-flatten puts!
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET n=10: LET j=1: LET col=1 20 FOR r=1 TO n 30 FOR j=j TO j+r-1 40 PRINT TAB (col);j; 50 LET col=col+3 60 NEXT j 70 PRINT 80 LET col=1 90 NEXT r
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#PHP
PHP
<?php $finalres = Array(); function permut($arr,$result=array()){ global $finalres; if(empty($arr)){ $finalres[] = implode("",$result); }else{ foreach($arr as $key => $val){ $newArr = $arr; $newres = $result; $newres[] = $val; unset($newArr[$key]); permut($newArr,$newres); } } } $givenPerms ...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#S-BASIC
S-BASIC
  rem - return p mod q function mod(p, q = integer) = integer end = p - q * (p/q)   comment return day of week (Sun = 0, Mon = 1, etc.) for a given Gregorian calendar date using Zeller's congruence end function dayofweek (mo, da, yr = integer) = integer var y, c, z = integer if mo < 3 then begin ...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Scala
Scala
object FindTheLastSundayOfEachMonth extends App { import java.util.Calendar._ val cal = getInstance   def lastSundaysOf(year: Int) = (JANUARY to DECEMBER).map{month => cal.set(year, month + 1, 1) // first day of next month (1 to 7).find{_ => cal.add(DAY_OF_MONTH, -1); cal.get(DAY_OF_WEEK) == SUNDA...
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#C.23
C#
class Program { public void FizzBuzzGo() { Boolean Fizz = false; Boolean Buzz = false; for (int count = 1; count <= 100; count ++) { Fizz = count % 3 == 0; Buzz = count % 5 == 0; if (Fizz && Buzz) { Console.WriteLine...
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Racket
Racket
  #lang racket (require srfi/19)   (define long-months '(1 3 5 7 8 10 12)) (define days #(sun mon tue wed thu fri sat))   (define (week-day date) (vector-ref days (date-week-day date)))   (define (five-weekends-a-month start end) (for*/list ([year (in-range start (+ end 1))] [month long-months] ...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Standard_ML
Standard ML
- fun cube x = Math.pow(x, 3.0); val cube = fn : real -> real - fun croot x = Math.pow(x, 1.0 / 3.0); val croot = fn : real -> real - fun compose (f, g) = fn x => f (g x); (* this is already implemented in Standard ML as the "o" operator = we could have written "fun compose (f, ...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Stata
Stata
function _sin(x) { return(sin(x)) }   function _asin(x) { return(asin(x)) }   function _cos(x) { return(cos(x)) }   function _acos(x) { return(acos(x)) }   function cube(x) { return(x*x*x) }   function cuberoot(x) { return(sign(x)*abs(x)^(1/3)) }   function compose(f,g,x) { return((*f)((*g)(x))) }   a=&_sin(),&_...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Mirah
Mirah
import java.util.ArrayList import java.util.List import java.util.Collection   def flatten(list: Collection) flatten(list, ArrayList.new) end def flatten(source: Collection, result: List)   source.each do |x| if x.kind_of?(Collection) flatten(Collection(x), result) else ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Picat
Picat
P1 = ["ABCD","CABD","ACDB","DACB","BCDA","ACBD", "ADCB","CDAB","DABC","BCAD","CADB","CDBA", "CBAD","ABDC","ADBC","BDCA","DCBA","BACD", "BADC","BDAC","CBDA","DBCA","DCAB"], Perms = permutations("ABCD"),  % ...  
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "time.s7i"; include "duration.s7i";   const proc: main is func local var integer: weekday is 1; # 1 for monday, 2 for tuesday, and so on up to 7 for sunday. var integer: year is 0; var integer: month is 1; var time: aDate is time.value; var time: selected is t...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Sidef
Sidef
var dt = require('DateTime'); var (year=2016) = ARGV.map{.to_i}...   for i in (1 .. 12) { var date = dt.last_day_of_month( year => year, month => i );   while (date.dow != 7) { date = date.subtract(days => 1); }   say date.ymd; }
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#C.2B.2B
C++
#include <iostream> #include <chrono>   int main() {   int fizz = 0, buzz = 0, fizzbuzz = 0;   bool isFizz = false;   auto startTime = std::chrono::high_resolution_clock::now();   for (unsigned int i = 1; i <= 4000000000; i++) { isFizz = false;   if (i % 3 == 0) { isFizz = true; fizz++; }   if (i % 5 ...