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/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#langur
langur
val .sieve = f(.limit) { if .limit < 2 { return [] }   var .composite = arr .limit, false .composite[1] = true   for .n in 2 to truncate(.limit ^/ 2) + 1 { if not .composite[.n] { for .k = .n^2; .k < .limit; .k += .n { .composite[.k] = true } } }   where f(.n) not .composite[.n], series .limit-1 }   writeln .sieve(100)
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#COBOL
COBOL
;; *bug* shall have a dynamic binding. (declaim (special *bug*))   (let ((shape "triangle") (*bug* "ant")) (flet ((speak () (format t "~% There is some ~A in my ~A!" *bug* shape))) (format t "~%Put ~A in your ~A..." *bug* shape) (speak)   (let ((shape "circle") (*bug* "cockroach")) (format t "~%Put ~A in your ~A..." *bug* shape) (speak))))
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Common_Lisp
Common Lisp
;; *bug* shall have a dynamic binding. (declaim (special *bug*))   (let ((shape "triangle") (*bug* "ant")) (flet ((speak () (format t "~% There is some ~A in my ~A!" *bug* shape))) (format t "~%Put ~A in your ~A..." *bug* shape) (speak)   (let ((shape "circle") (*bug* "cockroach")) (format t "~%Put ~A in your ~A..." *bug* shape) (speak))))
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Icon_and_Unicon
Icon and Unicon
procedure main() write("Creating: ",fName := !open("mktemp","rp")) write(f := open(fName,"w"),"Hello, world") close(f) end
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Java
Java
import java.io.File; import java.io.IOException;   public class CreateTempFile { public static void main(String[] args) { try { //create a temp file File temp = File.createTempFile("temp-file-name", ".tmp"); System.out.println("Temp file : " + temp.getAbsolutePath()); } catch(IOException e) { e.printStackTrace(); } } }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Liberty_BASIC
Liberty BASIC
'Notice that arrays are globally visible to functions. 'The sieve() function uses the flags() array. 'This is a Sieve benchmark adapted from BYTE 1985 ' May, page 286   size = 7000 dim flags(7001) start = time$("ms") print sieve(size); " primes found." print "End of iteration. Elapsed time in milliseconds: "; time$("ms")-start end   function sieve(size) for i = 0 to size if flags(i) = 0 then prime = i + i + 3 k = i + prime while k <= size flags(k) = 1 k = k + prime wend sieve = sieve + 1 end if next i end function
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Delphi
Delphi
private
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
set :a "global" if true:  !print a local :a "local"  !print a  !print getglobal :a !print a  
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#E
E
feature some_procedure(int: INTEGER; char: CHARACTER) local r: REAL i: INTEGER do -- r, i and s have scope here -- as well as int and char -- some_procedure and some_function additionally have scope here end   s: STRING   some_function(int: INTEGER): INTEGER do -- s and Result have scope here -- as well as int (int here differs from the int of some_procedure) -- some_procedure and some_function additionally have scope here end   -- s, some_procedure and some_function have scope here
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#11l
11l
F monkey_coconuts(sailors = 5) V nuts = sailors L V n0 = nuts [(Int, Int, Int)] wakes L(sailor) 0..sailors V (portion, remainder) = divmod(n0, sailors) wakes.append((n0, portion, remainder)) I portion <= 0 | remainder != (I sailor != sailors {1} E 0) nuts++ L.break n0 = n0 - portion - remainder L.was_no_break R (nuts, wakes)   L(sailors) [5, 6] V (nuts, wake_stats) = monkey_coconuts(sailors) print("\nFor #. sailors the initial nut count is #.".format(sailors, nuts)) print("On each waking, the nut count, portion taken, and monkeys share are:\n "wake_stats.map(ws -> String(ws)).join(",\n "))
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Julia
Julia
  msg = "Rosetta Code, Secure temporary file, implemented with Julia."   (fname, tio) = mktemp() println(fname, " created as a temporary file.") println(tio, msg) close(tio) println("\"", msg, "\" written to ", fname)  
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Kotlin
Kotlin
// version 1.1.2   import java.io.File   fun main(args: Array<String>) { try { val tf = File.createTempFile("temp", ".tmp") println(tf.absolutePath) tf.delete() } catch (ex: Exception) { println(ex.message) } }
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Lua
Lua
fp = io.tmpfile()   -- do some file operations   fp:close()
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Limbo
Limbo
implement Sieve;   include "sys.m"; sys: Sys; print: import sys; include "draw.m"; draw: Draw;   Sieve : module { init : fn(ctxt : ref Draw->Context, args : list of string); };   init (ctxt: ref Draw->Context, args: list of string) { sys = load Sys Sys->PATH;   limit := 201; sieve : array of int; sieve = array [201] of {* => 1}; (sieve[0], sieve[1]) = (0, 0);   for (n := 2; n < limit; n++) { if (sieve[n]) { for (i := n*n; i < limit; i += n) { sieve[i] = 0; } } }   for (n = 1; n < limit; n++) { if (sieve[n]) { print ("%4d", n); } else { print(" ."); }; if ((n%20) == 0) print("\n\n"); } }  
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Eiffel
Eiffel
feature some_procedure(int: INTEGER; char: CHARACTER) local r: REAL i: INTEGER do -- r, i and s have scope here -- as well as int and char -- some_procedure and some_function additionally have scope here end   s: STRING   some_function(int: INTEGER): INTEGER do -- s and Result have scope here -- as well as int (int here differs from the int of some_procedure) -- some_procedure and some_function additionally have scope here end   -- s, some_procedure and some_function have scope here
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Ela
Ela
pi # private pi = 3.14159   sum # private sum x y = x + y
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#AutoHotkey
AutoHotkey
loop, 2 { sailor := A_Index+4 while !result := Coco(sailor, A_Index) continue ; format output remain := result["Coconuts"] output := sailor " Sailors, Number of coconuts = " result["Coconuts"] "`n" loop % sailor { x := result["Sailor_" A_Index] output .= "Monkey gets 1, Sailor# " A_Index " hides (" remain "-1)/" sailor " = " x ", remainder = " (remain -= x+1) "`n" } output .= "Remainder = " result["Remaining"] "/" sailor " = " floor(result["Remaining"] / sailor) MsgBox % output } return   Coco(sailor, coconut){ result := [], result["Coconuts"] := coconut loop % sailor { if (Mod(coconut, sailor) <> 1) return result["Sailor_" A_Index] := Floor(coconut/sailor) coconut -= Floor(coconut/sailor) + 1 } if Mod(coconut, sailor) || !coconut return result["Remaining"] := coconut return result }
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ we get a tempname$ choosed from Windows a$=tempname$ Try ok { \\ we can use wide to export in utf-16le \\ without wide we export as Ansi (set Local to desired language) Rem Locale 1033 ' when no use of wide Open a$ for wide output exclusive as #f wait 10 \\ Notepad can't open, because we open it for exclusive use Win "Notepad", a$ Print #f, "something" Print "Press a key";Key$ Close #f } If error or not ok then Print Error$ Win "Notepad", a$ } Checkit    
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
tmp = OpenWrite[] Close[tmp]
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Nanoquery
Nanoquery
import Nanoquery.IO   def guaranteedTempFile() // create a file object to generate temp file names $namegen = new(File)   // generate a temp filename $tempname = $namegen.tempFileName()   // file names are generated with uuids so they shouldn't repeat // in the case that they do, generate new ones until the generated // filename is unique $tempfile = new(File, $tempname) while ($tempfile.exists()) $tempname = $namegen.tempFileName() $tempfile = new(File, $tempname) end   // create the file and lock it from writing $tempfile.create() lock $tempfile.fullPath()   // return the file reference return $tempfile end
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   runSample(arg) return   -- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . method makeTempFile(prefix = String, suffix = String null, startDir = String null) - public static signals IOException returns File if startDir \= null then fStartDir = File(startDir) else fStartDir = null ff = File.createTempFile(prefix, suffix, fStartDir) ff.deleteOnExit() -- make sure the file is deleted at termination return ff   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static do tempFiles = [ - makeTempFile('rexx'), - makeTempFile('rexx', '.rex'), - makeTempFile('rexx', null, './tmp') - ] loop fFile over tempFiles fName = fFile.getCanonicalPath() say 'Temporary file:' fName end fFile catch ex = IOException ex.printStackTrace() end return  
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#6502_Assembly
6502 Assembly
IF PROC x = ...; ... THEN # can call x here # PROC y = ...; ... GO TO l1 # invalid!! # ELSE # can call x here, but not y # ... l1: ... FI
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Lingo
Lingo
-- parent script "sieve" property _sieve   ---------------------------------------- -- @constructor ---------------------------------------- on new (me) me._sieve = [] return me end   ---------------------------------------- -- Returns list of primes <= n ---------------------------------------- on getPrimes (me, limit) if me._sieve.count<limit then me._primeSieve(limit) primes = [] repeat with i = 2 to limit if me._sieve[i] then primes.add(i) end repeat return primes end   ---------------------------------------- -- Sieve of Eratosthenes ---------------------------------------- on _primeSieve (me, limit) me._sieve = [0] repeat with i = 2 to limit me._sieve[i] = 1 end repeat c = sqrt(limit) repeat with i = 2 to c if (me._sieve[i]=0) then next repeat j = i*i -- start with square repeat while (j<=limit) me._sieve[j] = 0 j = j + i end repeat end repeat end
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Erlang
Erlang
  -module( a_module ).   -export( [double/1] ).   double( N ) -> add( N, N ).       add( N, N ) -> N + N.  
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#FreeBASIC
FreeBASIC
'Declares a integer variable and reserves memory to accommodate it Dim As Integer baseAge = 10 'Define a variable that has static storage Static As String person person = "Amy" 'Declare variables that are both accessible inside and outside procedures Dim Shared As String friend friend = "Susan" Dim Shared As Integer ageDiff = 3 Dim Shared As Integer extraYears = 5   Sub test() 'Declares a integer variable and reserves memory to accommodate it Dim As Integer baseAge = 30 'Define a variable that has static storage Static As String person person = "Bob" 'Declare a local variable distinct from a variable with global scope having the same name Static As Integer extraYears = 2   Print person; " and "; friend; " are"; baseAge; " and"; baseAge + ageDiff + extraYears; " years old." End Sub   test() Print person; " and "; friend; " are"; baseAge; " and"; baseAge + ageDiff + extraYears; " years old." Sleep
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#AWK
AWK
  # syntax: GAWK -f SAILORS_COCONUTS_AND_A_MONKEY_PROBLEM.AWK # converted from LUA BEGIN { for (n=2; n<=9; n++) { x = 0 while (!valid(n,x)) { x++ } printf("%d %d\n",n,x) } exit(0) } function valid(n,nuts, k) { k = n while (k != 0) { if ((nuts % n) != 1) { return(0) } k-- nuts = nuts - 1 - int(nuts / n) } return((nuts != 0) && (nuts % n == 0)) }  
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Bc
Bc
define coconuts(sailors, monkeys) { print "coconuts(", sailors, ", ", monkeys, ") = " if (sailors < 2 || monkeys < 1 || sailors <= monkeys) { return 0 } blue_cocos = sailors-1 pow_bc = blue_cocos^sailors x_cocos = pow_bc while ((x_cocos-blue_cocos)%sailors || (x_cocos-blue_cocos)/sailors < 1) { x_cocos += pow_bc } return (x_cocos/pow_bc*(sailors^sailors)-blue_cocos)*monkeys } scale = 0 coconuts(1, 1) coconuts(2, 1) coconuts(3, 1) coconuts(3, 2) coconuts(4, 1) coconuts(5, 1) coconuts(5, 4) coconuts(6, 1) coconuts(101, 1)
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Nim
Nim
import std/[os, tempfiles]   let (file, path) = createTempFile(prefix = "", suffix = "") echo path, " created." file.writeLine("This is a secure temporary file.") file.close() for line in path.lines: echo line removeFile(path)
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#OCaml
OCaml
# Filename.temp_file "prefix." ".suffix" ;; - : string = "/home/blue_prawn/tmp/prefix.301f82.suffix"
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Octave
Octave
[FID, MSG] = tmpfile(); % Return the file ID corresponding to a new temporary filename = tmpnam (...); % generates temporary file name, but does not open file [FID, NAME, MSG] = mkstemp (TEMPLATE, DELETE); % Return the file ID corresponding to a new temporary file with a unique name created from TEMPLATE.
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#ALGOL_68
ALGOL 68
IF PROC x = ...; ... THEN # can call x here # PROC y = ...; ... GO TO l1 # invalid!! # ELSE # can call x here, but not y # ... l1: ... FI
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#ALGOL_W
ALGOL W
# This program outputs a greeting BEGIN { sayhello() # Call the function defined below exit }   function sayhello { print "Hello World!" # Outputs a message to the terminal }
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#AWK
AWK
# This program outputs a greeting BEGIN { sayhello() # Call the function defined below exit }   function sayhello { print "Hello World!" # Outputs a message to the terminal }
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Axe
Axe
GOTO 50: REM THIS WILL WORK IMMEDIATELY
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#11l
11l
T City String name Float population   F (name, population) .name = name .population = population   V cities = [ City(‘Lagos’, 21), City(‘Cairo’, 15.2), City(‘Kinshasa-Brazzaville’, 11.3), City(‘Greater Johannesburg’, 7.55), City(‘Mogadishu’, 5.85), City(‘Khartoum-Omdurman’, 4.98), City(‘Dar Es Salaam’, 4.7), City(‘Alexandria’, 4.58), City(‘Abidjan’, 4.4), City(‘Casablanca’, 3.98) ]   F first_index(cities, condition) L(city) cities I condition(city) R L.index   F first(cities, condition) L(city) cities I condition(city) R city   print(first_index(cities, city -> city.name == ‘Dar Es Salaam’)) print(first(cities, city -> city.population < 5.0).name) print(first(cities, city -> city.name[0] == ‘A’).population)
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#LiveCode
LiveCode
function sieveE int set itemdel to comma local sieve repeat with i = 2 to int put i into sieve[i] end repeat put 2 into n repeat while n < int repeat with p = n to int step n if p = n then next repeat else put empty into sieve[p] end if end repeat add 1 to n end repeat combine sieve with comma filter items of sieve without empty sort items of sieve ascending numeric return sieve end sieveE
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Free_Pascal
Free Pascal
global var1 # used outside of procedures   procedure one() # a global procedure (the only kind) local var2 # used inside of procedures static var3 # also used inside of procedures end
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Go
Go
global var1 # used outside of procedures   procedure one() # a global procedure (the only kind) local var2 # used inside of procedures static var3 # also used inside of procedures end
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Haskell
Haskell
global var1 # used outside of procedures   procedure one() # a global procedure (the only kind) local var2 # used inside of procedures static var3 # also used inside of procedures end
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Befunge
Befunge
>2+:01p9>`#@_00v nvg10*g10:+>#1$< #>\:01g1-%#^_:0v -|:-1\+1<+/-1g1< 1>$01g.">-",,48v ^g10,+55<.,9.,*<
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Bracmat
Bracmat
( ( divmod = a b . !arg:(?a.?b)&(div$(!a.!b).mod$(!a.!b)) ) & ( overnight = ns nn result s q r .  !arg:(?ns.?nn) & :?result & 0:?s & whl ' ( !s+1:?s:~>!ns & divmod$(!nn.!ns):(?q.?r) & !r:1 & !q*(!ns+-1):?nn & !result (!s.!q.!r.!nn):?result ) & !s:>!ns & divmod$(!nn.!ns):(?q.0) & !result ) & ( minnuts = nsailors nnuts result sailor takes gives leaves .  !arg:?nsailors & 0:?nnuts & whl ' ( 1+!nnuts:?nnuts & ~(overnight$(!nsailors.!nnuts):?result) ) & out$(!nsailors ": " !nnuts) & whl ' ( !result:(?sailor.?takes.?gives.?leaves) ?result & out $ ( str $ ( " Sailor #"  !sailor " takes "  !takes ", giving "  !gives " to the monkey and leaves "  !leaves ) ) ) & out $ ( str $ ("In the morning, each sailor gets " !leaves*!nsailors^-1 " nuts") ) ) & 4:?n & whl ' ( 1+!n:~>6:?n & out$("Solution with " !n " sailors:") & minnuts$!n ) )
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Pascal
Pascal
Program TempFileDemo;   uses SysUtils;   var tempFile: text;   begin assign (Tempfile, GetTempFileName); rewrite (tempFile); writeln (tempFile, 5); close (tempFile); end.
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Perl
Perl
use File::Temp qw(tempfile); $fh = tempfile(); ($fh2, $filename) = tempfile(); # this file stays around by default print "$filename\n"; close $fh; close $fh2;
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Phix
Phix
without js -- (file i/o) pp(temp_file()) {integer fn, string name} = temp_file("myapp/tmp","data","log","wb") pp({fn,name}) close(fn) {} = delete_file(name)
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#BASIC
BASIC
GOTO 50: REM THIS WILL WORK IMMEDIATELY
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#bc
bc
f(1) /* First output line */ define f(x) { return(x) } f(3) /* Second output line */   define f(x) { return(x - 1) } f(3) /* Third output line */
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#C
C
  #include <stdio.h>   #define sqr(x) ((x) * (x)) #define greet printf("Hello There!\n")   int twice(int x) { return 2 * x; }   int main(void) { int x;   printf("This will demonstrate function and label scopes.\n"); printf("All output is happening through printf(), a function declared in the header stdio.h, which is external to this program.\n"); printf("Enter a number: "); if (scanf("%d", &x) != 1) return 0;   switch (x % 2) { default: printf("Case labels in switch statements have scope local to the switch block.\n"); case 0: printf("You entered an even number.\n"); printf("Its square is %d, which was computed by a macro. It has global scope within the translation unit.\n", sqr(x)); break; case 1: printf("You entered an odd number.\n"); goto sayhello; jumpin: printf("2 times %d is %d, which was computed by a function defined in this file. It has global scope within the translation unit.\n", x, twice(x)); printf("Since you jumped in, you will now be greeted, again!\n"); sayhello: greet; if (x == -1) goto scram; break; }   printf("We now come to goto, it's extremely powerful but it's also prone to misuse. Its use is discouraged and it wasn't even adopted by Java and later languages.\n");   if (x != -1) { x = -1; /* To break goto infinite loop. */ goto jumpin; }   scram: printf("If you are trying to figure out what happened, you now understand goto.\n"); return 0; }
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#8086_Assembly
8086 Assembly
.model small .stack 1024   .data Africa WORD LAGOS ;"jagged" arrays are the bane of assembly programming, so store the string's pointer here instead. WORD 2100H ;this is a bit cheaty but it's easier to store these as BCD whole numbers WORD CAIRO WORD 1520H WORD KB WORD 1130H WORD GJ WORD 0755H WORD MOGADISHU WORD 0585H WORD KO WORD 0498H WORD DES WORD 0470H WORD ALEXANDRIA WORD 0458H WORD ABIDJAN WORD 0440H WORD CASABLANCA WORD 0398H   LAGOS BYTE "Lagos",0 CAIRO BYTE "Cairo",0 KB BYTE "Kinshasa-Brazzaville",0 GJ BYTE "Greater Johannesburg",0 MOGADISHU BYTE "Mogadishu",0 KO BYTE "Khartoum-Omdurman",0 DES BYTE "Dar Es Salaam",0 ALEXANDRIA BYTE "Alexandria" ABIDJAN BYTE "Abidjan",0 CASABLANCA BYTE "Casablanca",0   .code start:   mov ax,@data mov ds,ax   mov ax,@code mov es,ax     cld ;String functions are set to auto-increment   mov ax,2 ;clear screen by reloading the video mode we're in int 10h   mov si,offset Africa   ;test 1: find the index of the city whose name is Dar-Es-Salaam   mov di,offset DES ;it's easier to test the equality of two pointers than of two strings. mov cx,10 ;ten cities to check mov bx,0 ;our counter   test_case_1: lodsw cmp ax,di ;compare to the pointer of Dar-Es_Salaam je done_test_case_1 add si,2 ;we know populations aren't going to match so skip them inc bx ;increment the counter loop test_case_1   done_test_case_1: mov al,bl call Printhex ;print the index of Dar-Es-Salaam call Newline ;print CRLF     ;test 2: print the name of the first city whose population is less than 5 million. mov si,offset Africa mov cx,10     test_case_2: lodsw ;we know that the struct goes city:pop so skip the first word. lodsw cmp ax,0500h jae skip sub si,4 ;point SI back to the city name mov si,[ds:si] call PrintString call NewLine jmp done_test_case_2   skip: loop test_case_2 done_test_case_2:     ;test 3: find the population of the first city in this list whose name starts with A mov si,offset Africa mov cx,10   test_case_3: lodsw push si mov si,ax lodsb cmp al,'A' pop si je FoundIt ;popping SI won't affect the compare result.   add si,2 ;skip population loop test_case_3         ExitDOS: mov ax,4C00h ;return to dos int 21h   FoundIt: lodsw mov dx,ax mov al,dh call Printhex_NoLeadingZeroes mov al,'.' ;we're faking floating point for simplicity's sake call PrintChar mov al,dl call PrintHex jmp ExitDos   end start
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Logo
Logo
to sieve :limit make "a (array :limit 2)  ; initialized to empty lists make "p [] for [i 2 :limit] [ if empty? item :i :a [ queue "p :i for [j [:i * :i] :limit :i] [setitem :j :a :i] ] ] output :p end print sieve 100  ; 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Icon_and_Unicon
Icon and Unicon
global var1 # used outside of procedures   procedure one() # a global procedure (the only kind) local var2 # used inside of procedures static var3 # also used inside of procedures end
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#J
J
A=: 1 B=: 2 C=: 3 F=: verb define A=:4 B=.5 D=.6 A+B+C+D ) F '' 18 A 4 B 2 D |value error
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Java
Java
public //any class may access this member directly   protected //only this class, subclasses of this class, //and classes in the same package may access this member directly   private //only this class may access this member directly   static //for use with other modifiers //limits this member to one reference for the entire JVM   //adding no modifier (sometimes called "friendly") allows access to the member by classes in the same package   // Modifier | Class | Package | Subclass | World // ------------|-------|---------|----------|------- // public | Y | Y | Y | Y // protected | Y | Y | Y | N // no modifier | Y | Y | N | N // private | Y | N | N | N   //method parameters are available inside the entire method   //Other declarations follow lexical scoping, //being in the scope of the innermost set of braces ({}) to them. //You may also create local scopes by surrounding blocks of code with braces.   public void function(int x){ //can use x here int y; //can use x and y here { int z; //can use x, y, and z here } //can use x and y here, but NOT z }
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#C
C
#include <stdio.h>   int valid(int n, int nuts) { int k; for (k = n; k; k--, nuts -= 1 + nuts/n) if (nuts%n != 1) return 0; return nuts && !(nuts%n); }   int main(void) { int n, x; for (n = 2; n < 10; n++) { for (x = 0; !valid(n, x); x++); printf("%d: %d\n", n, x); } return 0; }
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#PHP
PHP
$fh = tmpfile(); // do stuff with $fh fclose($fh); // file removed when closed   // or: $filename = tempnam('/tmp', 'prefix'); echo "$filename\n"; // open $filename and do stuff with it
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#PicoLisp
PicoLisp
: (out (tmp "foo") (println 123)) # Write tempfile -> 123   : (in (tmp "foo") (read)) # Read tempfile -> 123   : (let F (tmp "foo") (ctl F # Get exclusive lock (in F (let N (read) # Atomic increment (out F (println (inc N))) ) ) ) ) -> 124
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#PowerShell
PowerShell
  $tempFile = [System.IO.Path]::GetTempFileName() Set-Content -Path $tempFile -Value "FileName = $tempFile" Get-Content -Path $tempFile Remove-Item -Path $tempFile  
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Eiffel
Eiffel
--assume A, B and C to be valid classes class X feature -- alias for "feature {ANY}" -- ANY is the class at the top of the class hierarchy and all classes inherit from it -- features following this clause are given "global" scope: these features are visible to every class   feature {A, B, C, X} -- features following this clause are only visible to the specified classes (and their descendants) -- classes not in this set do not even know of the existence of these features   feature {A, B, C} -- similar to above, except other instances of X cannot access these features   feature {X} -- features following this clause are only visible to instances of X (and its descendants)   feature {NONE} -- NONE is the class at the bottom of the class hierarchy and inherits from every class -- features following this clause are only visible to this particular instance of X   end
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Erlang
Erlang
  -module( a_module ).   -export( [exported_function/0] ).   exported_function() -> 1 + local_function().   local_function() -> 2.  
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Factor
Factor
USE: math 2 2 +
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#8th
8th
[ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] var, cities-raw   "Index of first occurrence of 'Dar Es Salaam': " . "Dar Es Salaam" >r cities-raw @ ( "name" m:@ r@ s:= if drop . cr ;; then 2drop ) a:each drop rdrop   "The name of the first city in this list whose population is less than 5 million: " . 5 >r cities-raw @ ( nip "population" m:@ r@ n:< if "name" m:@ . cr break then drop ) a:each drop rdrop   "The population of the first city in this list whose name starts with the letter \"A\": " . 'A >r cities-raw @ ( nip "name" m:@ 0 s:@ r@ n:= if drop "population" m:@ . cr break then 2drop ) a:each drop rdrop   bye
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Logtalk
Logtalk
due to the use of mod (modulo = division) in the filter function.
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#JavaScript
JavaScript
  julia> function foo(n) x = 0 for i = 1:n local x # introduce a loop-local x x = i end x end foo (generic function with 1 method)   julia> foo(10) 0  
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Julia
Julia
  julia> function foo(n) x = 0 for i = 1:n local x # introduce a loop-local x x = i end x end foo (generic function with 1 method)   julia> foo(10) 0  
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Kotlin
Kotlin
// version 1.1.2   class SomeClass { val id: Int   companion object { private var lastId = 0 val objectsCreated get() = lastId }   init { id = ++lastId } }   fun main(args: Array<String>) { val sc1 = SomeClass() val sc2 = SomeClass() println(sc1.id) println(sc2.id) println(SomeClass.objectsCreated) }
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#C.23
C#
class Test { static bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } }   return nuts != 0 && (nuts % n == 0); }   static void Main(string[] args) { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) x++; System.Console.WriteLine(n + ": " + x); } } }
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#PureBasic
PureBasic
Procedure.s TempFile() Protected a, Result$   For a = 0 To 9999 Result$ = GetTemporaryDirectory() + StringField(GetFilePart(ProgramFilename()),1,".") Result$ + "_" + Str(ElapsedMilliseconds()) + "_(" + RSet(Str(a),4,"0") + ").tmp" If FileSize(Result$) = -1 ; -1 = File not found ProcedureReturn Result$ EndIf Next   ProcedureReturn "" EndProcedure     Define File, File$   File$ = TempFile() If File$ <> "" File = CreateFile(#PB_Any, File$) If File <> 0 WriteString(File, "Some temporary data here...") CloseFile(File) EndIf EndIf
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Python
Python
>>> import tempfile >>> invisible = tempfile.TemporaryFile() >>> invisible.name '<fdopen>' >>> visible = tempfile.NamedTemporaryFile() >>> visible.name '/tmp/tmpZNfc_s' >>> visible.close() >>> invisible.close()
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#FreeBASIC
FreeBASIC
package main   import ( "fmt" "runtime"   "ex" )   func main() { // func nested() { ... not allowed here   // this is okay, variable f declared and assigned a function literal. f := func() { // this mess prints the name of the function to show that it's an // anonymous function defined in package main pc, _, _, _ := runtime.Caller(0) fmt.Println(runtime.FuncForPC(pc).Name(), "here!") }   ex.X(f) // function value passed to exported function   // ex.x() non-exported function not visible here }
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Go
Go
package main   import ( "fmt" "runtime"   "ex" )   func main() { // func nested() { ... not allowed here   // this is okay, variable f declared and assigned a function literal. f := func() { // this mess prints the name of the function to show that it's an // anonymous function defined in package main pc, _, _, _ := runtime.Caller(0) fmt.Println(runtime.FuncForPC(pc).Name(), "here!") }   ex.X(f) // function value passed to exported function   // ex.x() non-exported function not visible here }
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#haskell
haskell
  add3 :: Int -> Int-> Int-> Int add3 x y z = add2 x y + z   add2 :: Int -> Int -> Int add2 x y = x + y   main :: putStrLn(show (add3 5 6 5))  
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   DEFINE PTR="CARD" DEFINE ENTRY_SIZE="4" DEFINE STX="$8E" DEFINE STA="$8D" DEFINE JSR="$20" DEFINE RTS="$60"   TYPE City=[ CARD name, ;CHAR ARRAY population] ;REAL POINTER   BYTE ARRAY cities(100) BYTE count=[0]   CHAR ARRAY nameParam ;param for name predicate REAL popParam ;param for population predicate CHAR letterParam ;param for letter predicate CITY POINTER c ;city used in predicates and actions BYTE index ;index of city used in index action   PTR FUNC GetItemAddr(BYTE index) PTR addr   addr=cities+index*ENTRY_SIZE RETURN (addr)   PROC Append(CHAR ARRAY n REAL POINTER p) City POINTER dst   dst=GetItemAddr(count) dst.name=n dst.population=p count==+1 RETURN   PROC InitData() REAL lg,ca,ki,gr,mo,kh,da,al,ab,cs   ValR("21.0",lg) ValR("15.2",ca) ValR("11.3",ki) ValR("7.53",gr) ValR("5.85",mo) ValR("4.98",kh) ValR("4.7",da) ValR("4.58",al) ValR("4.4",ab) ValR("3.98",cs)   Append("Lagos",lg) Append("Cairo",ca) Append("Kinshasa-Brazzaville",ki) Append("Greater Johannesburg",gr) Append("Mogadishu",mo) Append("Khartoum-Omdurman",kh) Append("Dar Es Salaam",da) Append("Alexandria",al) Append("Abidjan",ab) Append("Casablanca",cs) RETURN   BYTE FUNC NameEquals() RETURN (SCompare(c.name,nameParam)+1)   BYTE FUNC PopulationLess() REAL diff BYTE ARRAY x   RealSub(popParam,c.population,diff) x=diff IF (x(0)&$80)=$00 THEN RETURN (1) FI RETURN (0)   BYTE FUNC FirstLetter() CHAR ARRAY n   n=c.name IF n(0)>=1 AND n(1)=letterParam THEN RETURN (1) FI RETURN (0)   ;jump addr is stored in X and A registers BYTE FUNC Predicate=*(PTR jumpAddr) [STX Predicate+8 STA Predicate+7 JSR $00 $00 RTS]   PROC PrintIndex() PrintF("index=%I%E",index) RETURN   PROC PrintName() PrintF("name=%S%E",c.name) RETURN   PROC PrintPopulation() Print("population=") PrintRE(c.population) RETURN   ;jump addr is stored in X and A registers PROC Action=*(PTR jumpAddr) [STX Action+8 STA Action+7 JSR $00 $00 RTS]   PROC Find(PTR predicateFun,actionFun) FOR index=0 TO count-1 DO c=GetItemAddr(index) IF Predicate(predicateFun) THEN Action(actionFun) EXIT FI OD RETURN   PROC Main() Put(125) PutE() ;clear screen InitData()   nameParam="Dar Es Salaam" Find(NameEquals,PrintIndex)   ValR("5.0",popParam) Find(PopulationLess,PrintName)   letterParam='A Find(FirstLetter,PrintPopulation) RETURN
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Ada
Ada
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO;   procedure Search_A_List_Of_Records is function "+"(input : in String) return Unbounded_String renames To_Unbounded_String; function "+"(input : in Unbounded_String) return String renames To_String;   type City is record name : Unbounded_String; population : Float; end record;   type City_Array is array(Positive range <>) of City; type City_Array_Access is access City_Array;   type Cursor is record container : City_Array_Access; index : Natural; end record;   function Element(C : in Cursor) return City is begin if C.container = null or C.index = 0 then raise Constraint_Error with "No element."; end if;   return C.container.all(C.index); end Element;   function Index_0(C : in Cursor) return Natural is begin if C.container = null or C.index = 0 then raise Constraint_Error with "No element."; end if;   return C.index - C.container.all'First; end Index_0;   function Find (container : in City_Array; check : not null access function(Element : in City) return Boolean) return Cursor is begin for I in container'Range loop if check.all(container(I)) then return (new City_Array'(container), I); end if; end loop; return (null, 0); end;   function Dar_Es_Salaam(Element : in City) return Boolean is begin return Element.name = "Dar Es Salaam"; end Dar_Es_Salaam;   function Less_Than_Five_Million(Element : in City) return Boolean is begin return Element.population < 5.0; end Less_Than_Five_Million;   function Starts_With_A(Item : in City) return Boolean is begin return Element(Item.name, 1) = 'A'; end Starts_With_A;   cities : constant City_Array := ((+"Lagos", 21.0), (+"Cairo", 15.2), (+"Kinshasa-Brazzaville", 11.3), (+"Greater Johannesburg", 7.55), (+"Mogadishu", 5.85), (+"Khartoum-Omdurman", 4.98), (+"Dar Es Salaam", 4.7 ), (+"Alexandria", 4.58), (+"Abidjan", 4.4 ), (+"Casablanca", 3.98)); begin Ada.Text_IO.Put_Line(Index_0(Find(cities, Dar_Es_Salaam'Access))'Img); Ada.Text_IO.Put_Line(+Element(Find(cities, Less_Than_Five_Million'Access)).name); Ada.Text_IO.Put_Line(Element(Find(cities, Starts_With_A'Access)).population'Img); end Search_A_List_Of_Records;
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#LOLCODE
LOLCODE
HAI 1.2 CAN HAS STDIO?   HOW IZ I Eratosumthin YR Max I HAS A Siv ITZ A BUKKIT Siv HAS A SRS 1 ITZ 0 I HAS A Index ITZ 2 IM IN YR Inishul UPPIN YR Dummy WILE DIFFRINT Index AN SUM OF Max AN 1 Siv HAS A SRS Index ITZ 1 Index R SUM OF Index AN 1 IM OUTTA YR Inishul   I HAS A Prime ITZ 2 IM IN YR MainLoop UPPIN YR Dummy WILE BOTH SAEM Max AN BIGGR OF Max AN PRODUKT OF Prime AN Prime BOTH SAEM Siv'Z SRS Prime AN 1 O RLY? YA RLY Index R SUM OF Prime AN Prime IM IN YR MarkMultipulz UPPIN YR Dummy WILE BOTH SAEM Max AN BIGGR OF Max AN Index Siv'Z SRS Index R 0 Index R SUM OF Index AN Prime IM OUTTA YR MarkMultipulz OIC Prime R SUM OF Prime AN 1 IM OUTTA YR MainLoop   Index R 1 I HAS A First ITZ WIN IM IN YR PrintPrimes UPPIN YR Dummy WILE BOTH SAEM Max AN BIGGR OF Max AN Index BOTH SAEM Siv'Z SRS Index AN 1 O RLY? YA RLY First O RLY? YA RLY First R FAIL NO WAI VISIBLE ", "! OIC VISIBLE Index! OIC Index R SUM OF Index AN 1 IM OUTTA YR PrintPrimes VISIBLE "" IF U SAY SO   I IZ Eratosumthin YR 100 MKAY   KTHXBYE
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Liberty_BASIC
Liberty BASIC
  make "g 5  ; global   to proc :p make "h 4  ; also global local "l  ; local, no initial value localmake "m 3   sub 7 end   to sub :s  ; can see :g, :h, and :s  ; if called from proc, can also see :l and :m localmake "h 5  ; hides global :h within this procedure and those it calls end  
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Logo
Logo
  make "g 5  ; global   to proc :p make "h 4  ; also global local "l  ; local, no initial value localmake "m 3   sub 7 end   to sub :s  ; can see :g, :h, and :s  ; if called from proc, can also see :l and :m localmake "h 5  ; hides global :h within this procedure and those it calls end  
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Logtalk
Logtalk
  :- public(foo/1). % predicate can be called from anywhere   :- protected(bar/2). % predicate can be called from the declaring entity and its descendants   :- private(baz/3). % predicate can only be called from the declaring entity   :- object(object, % predicates declared in the protocol become private for the object implements(private::protocol)).   :- category(object, % predicates declared in the protocol become protected for the category implements(protected::protocol)).   :- protocol(extended, % no change to the scope of the predicates inherited from the extended protocol extends(public::minimal)).  
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#C.2B.2B
C++
#include <iostream>   bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } }   return nuts != 0 && (nuts % n == 0); }   int main() { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) { x++; } std::cout << n << ": " << x << std::endl; }   return 0; }
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Racket
Racket
  #lang racket (make-temporary-file)  
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Raku
Raku
use File::Temp;   # Generate a temp file in a temp dir my ($filename0,$filehandle0) = tempfile;   # specify a template for the filename # * are replaced with random characters my ($filename1,$filehandle1) = tempfile("******");   # Automatically unlink files at DESTROY (this is the default) my ($filename2,$filehandle2) = tempfile("******", :unlink);   # Specify the directory where the tempfile will be created my ($filename3,$filehandle3) = tempfile(:tempdir("/path/to/my/dir"));   # don't unlink this one my ($filename4,$filehandle4) = tempfile(:tempdir('.'), :!unlink);   # specify a prefix, a suffix, or both for the filename my ($filename5,$filehandle5) = tempfile(:prefix('foo'), :suffix(".txt"));
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Icon_and_Unicon
Icon and Unicon
a=. 1
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#J
J
a=. 1
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#jq
jq
def NAME: def NAME: 2; 1, NAME; # this calls the inner function, not the outer function   NAME # => 1, 2
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Julia
Julia
Type of scope | block/construct introducing this kind of scope ---------------------------------------------------------------- Global Scope | module, baremodule, at interactive prompt (REPL) Local Scope | Soft Local Scope: for, while, comprehensions, try-catch-finally, let Local Scope | Hard Local Scope: functions (either syntax, anonymous & do-blocks), struct, macro
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Kotlin
Kotlin
// version 1.1.2   // top level function visible anywhere within the current module internal fun a() = println("calling a")   object B { // object level function visible everywhere, by default fun f() = println("calling f") }   open class C { // class level function visible everywhere, by default fun g() = println("calling g")   // class level function only visible within C private fun h() = println("calling h")   // class level function only visible within C and its subclasses protected fun i() { println("calling i") println("calling h") // OK as h within same class // nested function in scope until end of i fun j() = println("calling j") j() } }   class D : C(), E { // class level function visible anywhere within the same module fun k() { println("calling k") i() // OK as C.i is protected m() // OK as E.m is public and has a body } }   interface E { fun m() { println("calling m") } }   fun main(args: Array<String>) { a() // OK as a is internal B.f() // OK as f is public val c = C() c.g() // OK as g is public but can't call h or i via c val d = D() d.k() // OK as k is public // labelled lambda expression assigned to variable 'l' val l = lambda@ { -> outer@ for (i in 1..3) { for (j in 1..3) { if (i == 3) break@outer // jumps out of outer loop if (j == 2) continue@outer // continues with next iteration of outer loop println ("i = $i, j = $j") } if (i > 1) println ("i = $i") // never executed } val n = 1 if (n == 1) return@lambda // returns from lambda println("n = $n") // never executed } l() // invokes lambda println("Good-bye!") // will be executed }
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#ALGOL_68
ALGOL 68
# Algol 68 doesn't have generic array searches but we can easily provide # # type specific ones #   # mode to hold the city/population info # MODE CITYINFO = STRUCT( STRING name, REAL population in millions );   # array of cities and populations # [ 1 : 10 ]CITYINFO cities := ( ( "Lagos", 21.0 ) , ( "Cairo", 15.2 ) , ( "Kinshasa-Brazzaville", 11.3 ) , ( "Greater Johannesburg", 7.55 ) , ( "Mogadishu", 5.85 ) , ( "Khartoum-Omdurman", 4.98 ) , ( "Dar Es Salaam", 4.7 ) , ( "Alexandria", 4.58 ) , ( "Abidjan", 4.4 ) , ( "Casablanca", 3.98 ) );   # operator to find the first city with the specified criteria, expressed as a procedure # # returns the index of the CITYINFO. We can also overload FIND so it can be applied to # # arrays of other types # # If there is no city matching the criteria, a value greater than the upper bound of # # the cities array is returned # PRIO FIND = 1; OP FIND = ( REF[]CITYINFO cities, PROC( REF CITYINFO )BOOL criteria )INT: BEGIN INT result := UPB cities + 1; BOOL found := FALSE; FOR pos FROM LWB cities TO UPB cities WHILE NOT found DO IF criteria( cities[ pos ] ) THEN found := TRUE; result := pos FI OD; result END # FIND # ;   # convenience operator to determine whether a STRING starts with a particular character # # returns TRUE if s starts with c, FALSE otherwise # PRIO STARTSWITH = 9; OP STARTSWITH = ( STRING s, CHAR c )BOOL: IF LWB s > UPB s THEN FALSE # empty string # ELSE s[ LWB s ] = c FI # STARTSWITH # ;   # find the 0-based index of Dar Es Salaam # # ( if we remove the "[ @ 0 ]", it would find the 1-based index ) # # NB - this assumes there is one - would get a subscript bound error if there isn't # print( ( "index of Dar Es Salaam (from 0): " , whole( cities[ @ 0 ] FIND ( ( REF CITYINFO city )BOOL: name OF city = "Dar Es Salaam" ), 0 ) , newline ) );   # find the first city with population under 5M # # NB - this assumes there is one - would get a subscript bound error if there isn't # print( ( name OF cities[ cities FIND ( ( REF CITYINFO city )BOOL: population in millions OF city < 5.0 ) ] , " has a population under 5M" , newline ) );   # find the population of the first city whose name starts with "A" # # NB - this assumes there is one - would get a subscript bound error if there isn't # print( ( "The population of a city named ""A..."" is: " , fixed( population in millions OF cities[ cities FIND ( ( REF CITYINFO city )BOOL: name OF city STARTSWITH "A" ) ], 0, 2 ) , newline ) )  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Lua
Lua
function erato(n) if n < 2 then return {} end local t = {0} -- clears '1' local sqrtlmt = math.sqrt(n) for i = 2, n do t[i] = 1 end for i = 2, sqrtlmt do if t[i] ~= 0 then for j = i*i, n, i do t[j] = 0 end end end local primes = {} for i = 2, n do if t[i] ~= 0 then table.insert(primes, i) end end return primes end
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Lua
Lua
foo = "global" -- global scope print(foo) local foo = "local module" -- local to the current block (which is the module) print(foo) -- local obscures the global print(_G.foo) -- but global still exists do -- create a new block print(foo) -- outer module-level scope still visible local foo = "local block" -- local to the current block (which is this "do") print(foo) -- obscures outer module-level local for foo = 1,2 do -- create another more-inner scope print("local for "..foo) -- obscures prior block-level local end -- and close the scope print(foo) -- prior block-level local still exists end -- close the block (and thus its scope) print(foo) -- module-level local still exists print(_G.foo) -- global still exists
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { M=1000 Function Global xz { =9999 } Module TopModule { \\ clear vars and static vars Clear M=500 Function Global xz { =10000 } Module Kappa { Static N=1 Global M=1234 x=1 z=1 k=1 Group Alfa { Private: x=10, z=20, m=100 Function xz { =.x*.z+M } Public: k=50 Module AddOne { .x++ .z++ .k++ Print .xz(), .m=100 } Module ResetValues { \\ use <= to change members, else using = we define local variables .x<=10 .z<=20 } } ' print 1465 Alfa.AddOne Print x=1, z=1, k=1, xz()=10000 Print N ' 1 first time, 2 second time N++ Push Alfa } Kappa Drop ' drop one alfa Kappa Print M=500 ' leave one alfa in stack of values } TopModule Read AlfaNew Try ok { AlfaNew.AddOne } \\ we get an error because M global not exist now \\ here M is Local. If Error or Not Ok Then Print Error$ ' Uknown M in .xz() in AlfaNew.AddOne Print M=1000, xz()=9999 For AlfaNew { Global M=1234 .ResetValues .AddOne ' now works because M exist as global, for this block } Print M=1000, xz()=9999 For This { Local M=50 M++ Print M=51 } Print M=1000 } Checkit List ' list of variables are empty Modules ? ' list of modules show two: A and A.Checkit Print Module$ ' print A  
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Clojure
Clojure
(defn solves-for? [sailors initial-coconut-count] (with-local-vars [coconuts initial-coconut-count, hidings 0] (while (and (> @coconuts sailors) (= (mod @coconuts sailors) 1) (var-set coconuts (/ (* (dec @coconuts) (dec sailors)) sailors)) (var-set hidings (inc @hidings))) (and (zero? (mod @coconuts sailors)) (= @hidings sailors))))   (doseq [sailors (range 5 7)] (let [start (first (filter (partial solves-for? sailors) (range)))] (println (str sailors " sailors start with " start " coconuts:")) (with-local-vars [coconuts start] (doseq [sailor (range sailors)] (let [hidden (/ (dec @coconuts) sailors)] (var-set coconuts (/ (* (dec @coconuts) (dec sailors)) sailors)) (println (str "\tSailor " (inc sailor) " hides " hidden " coconuts and gives 1 to the monkey, leaving " @coconuts ".")))) (println (str "\tIn the morning, each sailor gets another " (/ @coconuts sailors) " coconuts.")) (println "\tThe monkey gets no more.\n"))))  
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#REXX
REXX
/*REXX pgm secures (a temporary file), writes to it, displays the file, then deletes it.*/ parse arg tFID # . /*obtain optional argument from the CL.*/ if tFID=='' | tFID=="," then tFID= 'TEMP.FILE' /*Not specified? Then use the default.*/ if #=='' | #=="," then #= 6 /* " " " " " " */ call lineout tFID /*insure file is closed. */ rc= 0 say '··· creating file: ' tFID call lineout tFID,,1 /*insure file is open and at record 1. */ if rc\==0 then call ser rc 'creating file' tFID /*issue error if can't open the file. */ say '··· writing file: ' tFID   do j=1 for # /*write a half-dozen records to file. */ call lineout tFID, 'line' j /*write a record to the file. */ if rc\==0 then call ser rc 'writing file' tFID /*Have an error? Issue err msg.*/ end /*j*/   call lineout tFID /*close the file. */ say '··· reading/display file: ' tFID   do j=1 while lines(tFID)>0 /*read the entire file and display it. */ x= linein(tFID) /*read a record from the file. */ if rc\==0 then call ser rc 'reading file' tFID /*Have an error? Issue err msg.*/ say 'line ' j " of file" tFID":" x /*display a record to the term. */ end /*j*/   call lineout tFID /*close the file. */ say '··· erasing file: ' tFID 'ERASE' tFID /*erase the file. */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ ser: say; say '***error***' arg(1); say; exit 13 /*issue an error message to the term. */
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
#Ruby
Ruby
irb(main):001:0> require 'tempfile' => true irb(main):002:0> f = Tempfile.new('foo') => #<File:/tmp/foo20081226-307-10p746n-0> irb(main):003:0> f.path => "/tmp/foo20081226-307-10p746n-0" irb(main):004:0> f.close => nil irb(main):005:0> f.unlink => #<Tempfile: (closed)>
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Lua
Lua
function foo() print("global") end -- global scope by default foo() local function foo() print("local module") end -- local to the current block (which is the module) foo() -- local obscures the global _G.foo() -- bug global still exists do -- create a new block foo() -- outer module-level scope still visible local function foo() print("local block") end foo() -- obscures outer module-level local local function foo() -- redefine at local block level print("local block redef") local function foo() -- define again inside redef print("local block redef inner") end foo() -- call block-level redef inner end foo() -- call block-level redef end -- close the block (and thus its scope) foo() -- module-level local still exists _G.foo() -- global still exists
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#M2000_Interpreter
M2000 Interpreter
  Function Master { Module Alfa { Gosub 100 Global M=1000 \\ delta print 1000 delta End 100 Print Module(Beta)=False Print Module(Delta)=True Return } Group Object1 { Function Master { =M } Module Final Beta { \\ delta print 500 delta alfa() Sub alfa() Local N=@Kappa(3) Global M=N \\ delta print 1500 Delta Print This.Master()=1500 N=@Kappa(6) \\ change value of M, not shadow M like Global M M<=N \\ delta print 9000 Delta Print .Master()=9000 End Sub Function Kappa(K) =M*K End Function } } Module Global Delta { Goto name1 \\ a remark here   name1: Print Module(Alfa)=False Print Module(Beta)=False Print Module(Delta)=True Print M }   \\ This is the program K=100 Global M=500 Alfa Object1.Beta Print Object1.Master()=500 Print K=100, M=500 } Call Master() \\ No variables exist after the return from Master() Print Valid(M)=False  
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Nim
Nim
const C = block useless: 3
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#AppleScript
AppleScript
-- RECORDS   property lstCities : [¬ {|name|:"Lagos", population:21.0}, ¬ {|name|:"Cairo", population:15.2}, ¬ {|name|:"Kinshasa-Brazzaville", population:11.3}, ¬ {|name|:"Greater Johannesburg", population:7.55}, ¬ {|name|:"Mogadishu", population:5.85}, ¬ {|name|:"Khartoum-Omdurman", population:4.98}, ¬ {|name|:"Dar Es Salaam", population:4.7}, ¬ {|name|:"Alexandria", population:4.58}, ¬ {|name|:"Abidjan", population:4.4}, ¬ {|name|:"Casablanca", population:3.98}]     -- SEARCHES   -- nameIsDar :: Record -> Bool on nameIsDar(rec) |name| of rec = "Dar Es Salaam" end nameIsDar   -- popBelow :: Record -> Bool on popBelow5M(rec) population of rec < 5 end popBelow5M   -- nameBeginsWith :: Record -> Bool on nameBeginsWithA(rec) text 1 of |name| of rec = "A" end nameBeginsWithA     -- TEST on run   return {¬ findIndex(nameIsDar, lstCities), ¬ ¬ |name| of find(popBelow5M, lstCities), ¬ ¬ population of find(nameBeginsWithA, lstCities)}   end run         -- GENERIC FUNCTIONS   -- find :: (a -> Bool) -> [a] -> Maybe a on find(f, xs) tell mReturn(f) set lng to length of xs repeat with i from 1 to lng if lambda(item i of xs) then return item i of xs end repeat return missing value end tell end find   -- findIndex :: (a -> Bool) -> [a] -> Maybe Int on findIndex(f, xs) tell mReturn(f) set lng to length of xs repeat with i from 1 to lng if lambda(item i of xs) then return i end repeat return missing value end tell end findIndex   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property lambda : f end script end if end mReturn
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#Ada
Ada
generic type Data is private; package Bin_Trees is   type Tree_Type is private;   function Empty(Tree: Tree_Type) return Boolean; function Left (Tree: Tree_Type) return Tree_Type; function Right(Tree: Tree_Type) return Tree_Type; function Item (Tree: Tree_Type) return Data; function Empty return Tree_Type;   procedure Destroy_Tree(N: in out Tree_Type); function Tree(Value: Data) return Tree_Type; function Tree(Value: Data; Left, Right : Tree_Type) return Tree_Type;   private   type Node; type Tree_Type is access Node; type Node is record Left, Right: Tree_Type := null; Item: Data; end record;   end Bin_Trees;
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Lucid
Lucid
prime where prime = 2 fby (n whenever isprime(n)); n = 3 fby n+2; isprime(n) = not(divs) asa divs or prime*prime > N where N is current n; divs = N mod prime eq 0; end; end
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Module -> localize names of variables (lexical scoping) Block -> localize values of variables (dynamic scoping) Module creates new symbols: Module[{x}, Print[x]; Module[{x}, Print[x]] ] ->x$119 ->x$120 Block localizes values only; it does not create new symbols: x = 7; Block[{x=0}, Print[x]] Print[x] ->0 ->7
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#MUMPS
MUMPS
OUTER SET OUT=1,IN=0 WRITE "OUT = ",OUT,! WRITE "IN = ",IN,! DO INNER WRITE:$DATA(OUT)=0 "OUT was destroyed",! QUIT INNER WRITE "OUT (inner scope) = ",OUT,! WRITE "IN (outer scope) = ",IN,! NEW IN SET IN=3.14 WRITE "IN (inner scope) = ",IN,! KILL OUT QUIT
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.
#Nim
Nim
proc foo = echo "foo" # hidden proc bar* = echo "bar" # acessible   type MyObject = object name*: string # accessible secretAge: int # hidden