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/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#PicoLisp
PicoLisp
(in '(rec -q -c1 -tu16 - trim 0 2) # Record 2 seconds (make (while (rd 2) (link @) ) ) )
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Python
Python
import pyaudio   chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100   p = pyaudio.PyAudio()   stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk)   data = stream.read(chunk) print [ord(i)...
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Racket
Racket
  #lang racket (define (record n) (with-input-from-file "/dev/dsp" ( () (read-bytes n)))) (define (play bs) (display-to-file bs "/dev/dsp" #:exists 'append)) (play (record 65536))  
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Raku
Raku
use Audio::PortAudio; use Audio::Sndfile;   sub MAIN(Str $filename, Str :$source, Int :$buffer = 256) { my $pa = Audio::PortAudio.new; my $format = Audio::Sndfile::Info::Format::WAV +| Audio::Sndfile::Info::Subformat::PCM_16; my $out-file = Audio::Sndfile.new(:$filename, channels => 1, samplerate => 44100, ...
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h>   main: s="" load str ("archivo.txt") (s) println ( "File loaded:\n",s ) exit(0)  
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#AppleScript
AppleScript
set pathToTextFile to ((path to desktop folder as string) & "testfile.txt")   -- short way: open, read and close in one step set fileContent to read file pathToTextFile   -- long way: open a file reference, read content and close access set fileRef to open for access pathToTextFile set fileContent to read fileRef close...
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#PHP
PHP
<? class Foo { function bar(int $x) { } }   $method_names = get_class_methods('Foo'); foreach ($method_names as $name) { echo "$name\n"; $method_info = new ReflectionMethod('Foo', $name); echo $method_info; } ?>
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#PicoLisp
PicoLisp
  # The Rectangle class (class +Rectangle +Shape) # dx dy   (dm T (X Y DX DY) (super X Y) (=: dx DX) (=: dy DY) )   (dm area> () (* (: dx) (: dy)) )   (dm perimeter> () (* 2 (+ (: dx) (: dy))) )   (dm draw> () (drawRect (: x) (: y) (: dx) (: dy)) ) # Hypothetical function 'drawRect'  
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#Raku
Raku
class Foo { has $!a = now; has Str $.b; has Int $.c is rw; }   my $object = Foo.new: b => "Hello", c => 42;   for $object.^attributes { say join ", ", .name, .readonly, .container.^name, .get_value($object); }
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#REXX
REXX
j=2 abc.j= -4.12     say 'variable abc.2 (length' length(abc.2)')=' abc.2
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#Ruby
Ruby
class Foo @@xyz = nil def initialize(name, age) @name, @age = name, age end def add_sex(sex) @sex = sex end end   p foo = Foo.new("Angel", 18) #=> #<Foo:0x0000000305a688 @name="Angel", @age=18> p foo.instance_variables #=> [:@name, :@age] p foo.instance_variable_defined?(:@ag...
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Dyalect
Dyalect
func rep(s) { var x = s.Length() / 2 while x > 0 { if s.StartsWith(s.Substring(x)) { return x } x -= 1 } return 0 }   let m = [ "1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "1...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#F.23
F#
open System open System.Text.RegularExpressions   [<EntryPoint>] let main argv = let str = "I am a string" if Regex("string$").IsMatch(str) then Console.WriteLine("Ends with string.")   let rstr = Regex(" a ").Replace(str, " another ") Console.WriteLine(rstr) 0
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Factor
Factor
USING: io kernel prettyprint regexp ; IN: rosetta-code.regexp   "1000000" R/ 10+/ matches? .  ! Does the entire string match the regexp? "1001" R/ 10+/ matches? . "1001" R/ 10+/ re-contains? . ! Does the string contain the regexp anywhere?   "blueberry pie" R/ \p{alpha}+berry/ "pumpkin" re-replace print
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#AutoIt
AutoIt
#AutoIt Version: 3.2.10.0 $mystring="asdf" $reverse_string = "" $string_length = StringLen($mystring)   For $i = 1 to $string_length $last_n_chrs = StringRight($mystring, $i) $nth_chr = StringTrimRight($last_n_chrs, $i-1) $reverse_string= $reverse_string & $nth_chr Next   MsgBox(0, "Reversed string is:", $rev...
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Lean
Lean
def repeat : ℕ → (ℕ → string) → string | 0 f  := "done" | (n + 1) f := (f n) ++ (repeat n f)     #eval repeat 5 $ λ b : ℕ , "me "  
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#LiveCode
LiveCode
rep "answer",3   command rep x,n repeat n times do merge("[[x]] [[n]]") end repeat end rep
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Harbour
Harbour
FRename( "input.txt","output.txt") // or RENAME input.txt TO output.txt   FRename( hb_ps() + "input.txt", hb_ps() + "output.txt")
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Haskell
Haskell
import System.IO import System.Directory   main = do renameFile "input.txt" "output.txt" renameDirectory "docs" "mydocs" renameFile "/input.txt" "/output.txt" renameDirectory "/docs" "/mydocs"
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Groovy
Groovy
def text = new StringBuilder() .append('---------- Ice and Fire ------------\n') .append(' \n') .append('fire, in end will world the say Some\n') .append('ice. in say Some \n') .append('desire of tasted I\'ve what From \n') .append('fire....
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Quackery
Quackery
[ $ "" swap witheach [ dup char A char M 1+ within over char a char m 1+ within or iff [ 13 + ] else [ dup char N char Z 1+ within over char n char z 1+ within or if [ 13 - ] ] join ] ] is rot-13 ( $ --> $ )
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#PowerBASIC
PowerBASIC
FUNCTION toRoman(value AS INTEGER) AS STRING DIM arabic(0 TO 12) AS INTEGER DIM roman(0 TO 12) AS STRING ARRAY ASSIGN arabic() = 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ARRAY ASSIGN roman() = "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"   DIM i AS INTEGER DI...
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func integer: ROMAN parse (in string: roman) is func result var integer: arabic is 0; local var integer: index is 0; var integer: number is 0; var integer: lastval is 0; begin for index range length(roman) downto 1 do case roman[index] of when {'...
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Ceylon
Ceylon
shared void repeatAString() { print("ha".repeat(5)); }
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Frink
Frink
  divMod[a, b] := [a div b, a mod b]   [num, remainder] = divMod[10, 3]  
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#FunL
FunL
def addsub( x, y ) = (x + y, x - y)   val (sum, difference) = addsub( 33, 12 )   println( sum, difference, addsub(33, 12) )
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AWK
AWK
$ awk 'BEGIN{split("a b c d c b a",a);for(i in a)b[a[i]]=1;r="";for(i in b)r=r" "i;print r}' a b c d
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#BCPL
BCPL
get "libhdr"   // Generate the N'th term of the Recaman sequence // given terms 0 to N-1. let generate(a, n) be a!n := n=0 -> 0, valof $( let subterm = a!(n-1) - n let addterm = a!(n-1) + n if subterm <= 0 resultis addterm for i=0 to n-1 if a!i = subterm resultis addterm ...
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#C
C
#include <stdio.h> #include <stdlib.h> #include <gmodule.h>   typedef int bool;   int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_e...
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#ActionScript
ActionScript
public function RREF():Matrix { var lead:uint, i:uint, j:uint, r:uint = 0;   for(r = 0; r < rows; r++) { if(columns <= lead) break; i = r;   while(_m[i][lead] == 0) { i++;   if(rows == i) { i = r; lead++;   if(columns == lead) ...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT"   PROC Euler(REAL POINTER e) REAL x   IntToReal(1,x) Exp(x,e) RETURN   PROC Main() REAL a,b,c INT i   Put(125) PutE() ;clear screen MathInit()   Euler(a) Print("e=") PrintR(a) PrintE(" by Exp(1)")   ValR("2",a) Sqrt(a,b) Print("Sqrt(") PrintR(a) Print(")=") PrintR(b...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#ActionScript
ActionScript
Math.E; //e Math.PI; //pi Math.sqrt(u); //square root of u Math.log(u); //natural logarithm of u Math.exp(u); //e to the power of u Math.abs(u); //absolute value of u Math.floor(u);//floor of u Math.ceil(u); //ceiling of u Math.pow(u,v);//u to the power of v
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#C.2B.2B
C++
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list>   void deleteLines( const std::string & , int , int ) ;   int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; ...
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Scala
Scala
import java.io.{File, IOException} import javax.sound.sampled.{AudioFileFormat, AudioFormat, AudioInputStream} import javax.sound.sampled.{AudioSystem, DataLine, LineUnavailableException, TargetDataLine}   object SoundRecorder extends App { // record duration, in milliseconds final val RECORD_TIME = 60000 // 1 minu...
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Arturo
Arturo
contents: read "input.txt"
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#ATS
ATS
val s = fileref_get_file_string (stdin_ref)
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Python
Python
import inspect   # Sample classes for inspection class Super(object): def __init__(self, name): self.name = name   def __str__(self): return "Super(%s)" % (self.name,)   def doSup(self): return 'did super stuff'   @classmethod def cls(cls): return 'cls method (in sup)'   @classmethod def s...
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#Scala
Scala
object ListProperties extends App { private val obj = new { val examplePublicField: Int = 42 private val examplePrivateField: Boolean = true } private val clazz = obj.getClass   println("All public methods (including inherited):") clazz.getFields.foreach(f => println(s"${f}\t${f.get(obj)}"))   print...
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#Smalltalk
Smalltalk
someObject class instVarNames
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#Tcl
Tcl
% package require Tk 8.6.5 % . configure {-bd -borderwidth} {-borderwidth borderWidth BorderWidth 0 0} {-class class Class Toplevel Tclsh} {-menu menu Menu {} {}} {-relief relief Relief flat flat} {-screen screen Screen {} {}} {-use use Use {} {}} {-background background Background #d9d9d9 #d9d9d9} {-bg -background} ...
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#EchoLisp
EchoLisp
  (lib 'list) ;; list-rotate   ;; a list is a rep-list if equal? to itself after a rotation of lam units ;; lam <= list length / 2 ;; truncate to a multiple of lam before rotating ;; try cycles in decreasing lam order (longest wins)   (define (cyclic? cyclic) (define len (length cyclic)) (define trunc null)   ...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Forth
Forth
include ffl/rgx.fs   \ Create a regular expression variable 'exp' in the dictionary   rgx-create exp   \ Compile an expression   s" Hello (World)" exp rgx-compile [IF] .( Regular expression successful compiled.) cr [THEN]   \ (Case sensitive) match a string with the expression   s" Hello World" exp rgx-cmatch? [IF] ...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#FreeBASIC
FreeBASIC
  Dim As String text = "I am a text" If Right(text, 4) = "text" Then Print "'" + text + "' ends with 'text'" End If   Dim As Integer i = Instr(text, "am") text = Left(text, i - 1) + "was" + Mid(text, i + 2) Print "replace 'am' with 'was' = " + text Sleep  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Avail
Avail
"asfd" reversed
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Lua
Lua
function myFunc () print("Sure looks like a function in here...") end   function rep (func, times) for count = 1, times do func() end end   rep(myFunc, 4)  
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
repeat[f_, n_] := Do[f[], {n}]; repeat[Print["Hello, world!"] &, 5];
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#HicEst
HicEst
WRITE(FIle='input.txt', REName='.\output.txt') SYSTEM(DIR='E:\HicEst\Rosetta') WRITE(FIle='.\docs', REName='.\mydocs')   WRITE(FIle='\input.txt', REName='\output.txt') SYSTEM(DIR='\') WRITE(FIle='\docs', REName='\mydocs')
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Icon_and_Unicon
Icon and Unicon
every dir := !["./","/"] do { rename(f := dir || "input.txt", dir || "output.txt") |stop("failure for file rename ",f) rename(f := dir || "docs", dir || "mydocs") |stop("failure for directory rename ",f) }
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Haskell
Haskell
  revstr :: String -> String revstr = unwords . reverse . words -- point-free style --equivalent: --revstr s = unwords (reverse (words s))   revtext :: String -> String revtext = unlines . map revstr . lines -- applies revstr to each line independently   test = revtext "---------- Ice and Fire ------------\n\ \...
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#R
R
rot13 <- function(x) { old <- paste(letters, LETTERS, collapse="", sep="") new <- paste(substr(old, 27, 52), substr(old, 1, 26), sep="") chartr(old, new, x) } x <- "The Quick Brown Fox Jumps Over The Lazy Dog!.,:;'#~[]{}" rot13(x) # "Gur Dhvpx Oebja Sbk Whzcf Bire Gur Ynml Qbt!.,:;'#~[]{}" x2 <- paste(letters, ...
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#PowerShell
PowerShell
  Filter ToRoman { $output = ''   if ($_ -ge 4000) { throw 'Number too high' }   $current = 1000 $subtractor = 'M' $whole = $False $decimal = $_ 'C','D','X','L','I','V',' ' ` | %{ $divisor = $current if ($whole = !$whole) { $current /= 10 $subtractor = $_ + $subtractor[0] $_ = $subtractor[1] }...
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#SenseTalk
SenseTalk
function RomanNumeralsDecode numerals put { "M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1 } into values   put 0 into total repeat with each character letter of numerals if values.(character the counter + 1 of numerals) is less than or equal to values.(letter) add values.(letter...
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Clipper
Clipper
Replicate( "Ha", 5 )
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Clojure
Clojure
(apply str (repeat 5 "ha"))
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#FutureBasic
FutureBasic
  include "ConsoleWindow"   local fn ReturnMultipleValues( strIn as Str255, strOut as ^Str255, letterCount as ^long ) dim as Str255 s   // Test if incoming string is empty, and exit function if it is if strIn[0] == 0 then exit fn   // Prepend this string to incoming string and return it s = "Here is your original strin...
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#F.C5.8Drmul.C3.A6
Fōrmulæ
func addsub(x, y int) (int, int) { return x + y, x - y }
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#BASIC256
BASIC256
  arraybase 1 max = 10 dim res(max) dim dat(max) dat[1] = 1: dat[2] = 2: dat[3] = 1: dat[4] = 4: dat[5] = 5 dat[6] = 2: dat[7] = 15: dat[8] = 1: dat[9] = 3: dat[10] = 4 res[1] = dat[1]   cont = 1 posic = 1 while posic < max posic += 1 esnuevo = 1 indice = 1 while indice <= cont and esnuevo = 1 if dat[posic] = res...
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#C.23
C#
using System; using System.Collections.Generic;   namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; ...
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#Ada
Ada
generic type Element_Type is private; Zero : Element_Type; with function "-" (Left, Right : in Element_Type) return Element_Type is <>; with function "*" (Left, Right : in Element_Type) return Element_Type is <>; with function "/" (Left, Right : in Element_Type) return Element_Type is <>; package Matrice...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Ada
Ada
Ada.Numerics.e -- Euler's number Ada.Numerics.pi -- pi sqrt(x) -- square root log(x, base) -- logarithm to any specified base exp(x) -- exponential abs(x) -- absolute value S'floor(x) -- Produces the floor of an instance of subtype S S'ceiling(x) -- Produces the ceiling of an insta...
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Clojure
Clojure
(require '[clojure.java.io :as jio] '[clojure.string :as str])   (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-...
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Tcl
Tcl
package require sound   # Helper to do a responsive wait proc delay t {after $t {set ::doneDelay ok}; vwait ::doneDelay}   # Make an in-memory recording object set recording [snack::sound -encoding "Lin16" -rate 44100 -channels 1]   # Set it doing the recording, wait for a second, and stop $recording record -append tru...
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Wee_Basic
Wee Basic
print 1 "Recording..." micrec print 1 "Playing..." micpla end
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#AutoHotkey
AutoHotkey
  fileread, varname, C:\filename.txt ; adding "MsgBox %varname%" (no quotes) to the next line will display the file contents.
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#AutoIt
AutoIt
  $fileOpen = FileOpen("file.txt") $fileRead = FileRead($fileOpen) FileClose($fileOpen)  
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Raku
Raku
class Foo { method foo ($x) { } method bar ($x, $y) { } method baz ($x, $y?) { } }   my $object = Foo.new;   for $object.^methods { say join ", ", .name, .arity, .count, .signature.gist }
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Reflection   Module Module1   Class TestClass Private privateField = 7 Public ReadOnly Property PublicNumber = 4 Private ReadOnly Property PrivateNumber = 2 End Class   Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable Return From...
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Elixir
Elixir
defmodule Rep_string do def find(""), do: IO.puts "String was empty (no repetition)" def find(str) do IO.puts str rep_pos = Enum.find(div(String.length(str),2)..1, fn pos -> String.starts_with?(str, String.slice(str, pos..-1)) end) if rep_pos && rep_pos>0 do IO.puts String.duplicate(" ",...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Frink
Frink
  line = "My name is Inigo Montoya."   for [first, last] = line =~ %r/my name is (\w+) (\w+)/ig { println["First name is: $first"] println["Last name is: $last"] }  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#AWK
AWK
function reverse(s) { p = "" for(i=length(s); i > 0; i--) { p = p substr(s, i, 1) } return p }   BEGIN { print reverse("edoCattesoR") }
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#min
min
("Hello" puts!) 3 times
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#MiniScript
MiniScript
sayHi = function() print "Hi!" end function   rep = function(f, n) for i in range(1, n) f end for end function   rep @sayHi, 3
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Io
Io
  // rename file in current directory f := File with("input.txt") f moveTo("output.txt")   // rename file in root directory f := File with("/input.txt") f moveTo("/output.txt")   // rename directory in current directory d := Directory with("docs") d moveTo("mydocs")   // rename directory in root directory d := Director...
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#J
J
frename=: 4 : 0 if. x -: y do. return. end. if. IFUNIX do. hostcmd=. [: 2!:0 '('"_ , ] , ' || true)'"_ hostcmd 'mv "',y,'" "',x,'"' else. 'kernel32 MoveFileA i *c *c' 15!:0 y;x end. )
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Icon_and_Unicon
Icon and Unicon
procedure main() every write(rWords(&input)) end   procedure rWords(f) every !f ? { every (s := "") := genWords() || s suspend s } end   procedure genWords() while w := 1(tab(upto(" \t")),tab(many(" \t"))) || " " do suspend w end
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Racket
Racket
  #!/usr/bin/env racket #lang racket/base   (define (run i o) (for ([ch (in-producer regexp-match #f #rx#"[a-zA-Z]" i 0 #f o)]) (define b (bytes-ref (car ch) 0)) (define a (if (< b 96) 65 97)) (write-byte (+ (modulo (+ 13 (- b a)) 26) a))))   (require racket/cmdline) (command-line #:help-labels "(\"-\" s...
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Prolog
Prolog
:- use_module(library(clpfd)).   roman :- LA = [ _ , 2010, _, 1449, _], LR = ['MDCCLXXXIX', _ , 'CX', _, 'MDCLXVI'], maplist(roman, LA, LR), maplist(my_print,LA, LR).     roman(A, R) :- A #> 0, roman(A, [u, t, h, th], LR, []), label([A]), parse_Roman(CR, LR, []), atom_chars(R, CR)....
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Sidef
Sidef
func roman2arabic(roman) {   var arabic = 0 var last_digit = 1000   static m = Hash( I => 1, V => 5, X => 10, L => 50, C => 100, D => 500, M => 1000, )   roman.uc.chars.map{m{_} \\ 0}.each { |digit| if (last_digit < digit) {...
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. REPEAT-PROGRAM. DATA DIVISION. WORKING-STORAGE SECTION. 77 HAHA PIC A(10). PROCEDURE DIVISION. MOVE ALL 'ha' TO HAHA. DISPLAY HAHA. STOP RUN.
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Go
Go
func addsub(x, y int) (int, int) { return x + y, x - y }
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Groovy
Groovy
def addSub(x,y) { [ sum: x+y, difference: x-y ] }
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#BBC_BASIC
BBC BASIC
DIM list$(15) list$() = "Now", "is", "the", "time", "for", "all", "good", "men", \ \ "to", "come", "to", "the", "aid", "of", "the", "party." num% = FNremoveduplicates(list$()) FOR i% = 0 TO num%-1 PRINT list$(i%) " " ; NEXT PRINT END   DEF FNremovedu...
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#C.2B.2B
C++
#include <iostream> #include <ostream> #include <set> #include <vector>   template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { ...
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#Aime
Aime
rref(list l, integer rows, columns) { integer e, f, i, j, lead, r; list u, v;   lead = r = 0; while (r < rows && lead < columns) { i = r; while (!l.q_list(i)[lead]) { i += 1; if (i == rows) { i = r; lead += 1; if (le...
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Aime
Aime
# e exp(1); # pi 2 * asin(1);   sqrt(x); log(x); exp(x); fabs(x); floor(x); ceil(x); pow(x, y);
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#ALGOL_68
ALGOL 68
REAL x:=exp(1), y:=4*atan(1); printf(($g(-8,5)"; "$, exp(1), # e # pi, # pi # sqrt(x), # square root # log(x), # logarithm base 10 # ln(x), # natural logarithm # exp(x), # exponential # ABS x, # absolute value # ENTIER x, # floor # -ENTIER -x, # ceiling # ...
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Common_Lisp
Common Lisp
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) ;; Open a temp file to write the result to (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) ;; Open the original file...
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Wren
Wren
/* record_sound.wren */   class C { foreign static getInput(maxSize)   foreign static arecord(args)   foreign static aplay(name) }   var name = "" while (name == "") { System.write("Enter output file name (without extension) : ") name = C.getInput(80) } name = name + ".wav"   var rate = 0 while (!ra...
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { ## empty record separate, RS=""; ## read line (i.e. whole file) into $0 getline; ## print line number and content of line print "=== line "NR,":",$0; } { ## no further line is read printed print "=== line "NR,":",$0; }
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#BaCon
BaCon
content$ = LOAD$(filename$)
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Ring
Ring
  # Project : Reflection/List methods   o1 = new test aList = methods(o1) for x in aList cCode = "o1."+x+"()" eval(cCode) next Class Test func f1 see "hello from f1" + nl func f2 see "hello from f2" + nl func f3 see "hello from f3" + nl func f4 see "hello from f4" + nl  
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Ruby
Ruby
# Sample classes for reflection class Super CLASSNAME = 'super'   def initialize(name) @name = name def self.superOwn 'super owned' end end   def to_s "Super(#{@name})" end   def doSup 'did super stuff' end   def self.superClassStuff 'did super class stuff' end   protec...
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#Wren
Wren
#! instance_methods(m, n, o) #! instance_properties(p, q, r) class C { construct new() {}   m() {}   n() {}   o() {}   p {}   q {}   r {} }   var c = C.new() // create an object of type C System.print("List of properties available for object 'c':") for (property in c.type.attributes.self["instance_...
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#zkl
zkl
properties:=List.properties; properties.println(); List(1,2,3).property(properties[0]).println(); // get value List(1,2,3).Property(properties[0])().println(); // method that gets value List(1,2,3).BaseClass(properties[0]).println(); // another way to get value
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Excel
Excel
REPCYCLES =LAMBDA(s, LET( n, LEN(s), xs, FILTERP( LAMBDA(pfx, s = TAKECYCLESTRING(n)(pfx) ) )( TAILCOLS( INITS( MID(s, 1, QUOTIENT(n, 2)) ) ) ),   IF(ISERROR(xs)...
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Gambas
Gambas
Public Sub Main() Dim sString As String = "Hello world!"   If sString Ends "!" Then Print sString & " ends with !" If sString Begins "Hel" Then Print sString & " begins with 'Hel'"   sString = Replace(sString, "world", "moon")   Print sString   End
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#GeneXus
GeneXus
&string = &string.ReplaceRegEx("^\s+|\s+$", "") // it's a trim! &string = &string.ReplaceRegEx("Another (Match)", "Replacing $1") // Using replace groups
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Babel
Babel
strrev: { str2ar ar2ls reverse ls2lf ar2str }
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#.D0.9C.D0.9A-61.2F52
МК-61/52
1 П4   3 ^ 1 6 ПП 09 С/П   П7 <-> П0 КПП7 L0 12 В/О   ИП4 С/П КИП4 В/О
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Modula-2
Modula-2
MODULE Repeat; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   TYPE F = PROCEDURE;   PROCEDURE Repeat(fun : F; c : INTEGER); VAR i : INTEGER; BEGIN FOR i:=1 TO c DO fun END END Repeat;   PROCEDURE Print; BEGIN WriteString("Hello"); WriteLn END Print;   BEGIN Repeat(Print, 3);   Read...