/*REXX program removes any duplicate elements (items) that are in a list (using a hash).*/
$= '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2'    /*item list.*/
say 'original list:'     $
say right( words($), 17, '─')    'words in the original list.'
z=;                              @.=             /*initialize the NEW list & index list.*/
     do j=1  for words($);       y= word($, j)   /*process the words (items) in the list*/
     if @.y==''  then z= z y;    @.y= .          /*Not duplicated? Add to Z list,@ array*/
     end   /*j*/
say
say 'modified list:'     space(z)                /*stick a fork in it,  we're all done. */
say right( words(z), 17, '─')    'words in the modified list.'


list = ["Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "the", "party."]
for i = 1 to len(list)
    for j = i + 1 to len(list)
        if list[i] = list[j] del(list, j) j-- ok
    next
next

for n = 1 to len(list)
    see list[n] + " "
next
see nl


a$ = "2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2"

for i = 1 to len(a$)
  a1$ = word$(a$,i)
  if a1$ = "" then exit for
  for i1 = 1 to len(b$)
    if a1$ = word$(b$,i1) then [nextWord]
  next i1
  b$ = b$ + a1$ + " "
[nextWord]
next i

 print "Dups:";a$
 print "No Dups:";b$


use std::collections::HashSet;
use std::hash::Hash;

fn remove_duplicate_elements_hashing<T: Hash + Eq>(elements: &mut Vec<T>) {
    let set: HashSet<_> = elements.drain(..).collect();
    elements.extend(set.into_iter());
}

fn remove_duplicate_elements_sorting<T: Ord>(elements: &mut Vec<T>) {
    elements.sort_unstable(); // order does not matter
    elements.dedup();
}

fn main() {
    let mut sample_elements = vec![0, 0, 1, 1, 2, 3, 2];
    println!("Before removal of duplicates : {:?}", sample_elements);
    remove_duplicate_elements_sorting(&mut sample_elements);
    println!("After removal of duplicates : {:?}", sample_elements);
}


val list = List(1,2,3,4,2,3,4,99)
val l2 = list.distinct
// l2: scala.List[scala.Int] = List(1,2,3,4,99)

val arr = Array(1,2,3,4,2,3,4,99)
val arr2 = arr.distinct
// arr2: Array[Int] = Array(1, 2, 3, 4, 99)


(define (remove-duplicates l)
  (cond ((null? l)
         '())
        ((member (car l) (cdr l))
         (remove-duplicates (cdr l)))
        (else
         (cons (car l) (remove-duplicates (cdr l))))))

(remove-duplicates '(1 2 1 3 2 4 5))


$ include "seed7_05.s7i";

const proc: main is func
  local
    const array integer: data is [] (1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2);
    var set of integer: dataSet is (set of integer).value;
    var integer: number is 0;
  begin
    for number range data do
      incl(dataSet, number);
    end for;
    writeln(dataSet);
  end func;


set = new('set')
* Add all the elements of the array to the set.
add(set,array)


var ary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant'];
say ary.uniq.dump;
say ary.last_uniq.dump;


"Example of creating a collection"
|a|
a := #( 1 1 2 'hello' 'world' #symbol #another 2 'hello' #symbol ).
a asSet.


function undupe(arr) {
	var t = {};
	foreach(arr, function(key, val) {
		t[val] = true;
	});

	var r = {};
	foreach(t, function(key) {
		r[sizeof r] = key;
	});

	return r;
}


/*
This code is an implementation of "Remove duplicate elements" in SQL ORACLE 19c
p_in_str    -- input string
p_delimiter -- delimeter
*/
WITH
  FUNCTION remove_duplicate_elements(p_in_str IN varchar2, p_delimiter IN varchar2 DEFAULT ',') RETURN varchar2 IS
  v_in_str varchar2(32767) := REPLACE(p_in_str,p_delimiter,',');
  v_res    varchar2(32767);
BEGIN
  --
  EXECUTE immediate 'select listagg(distinct cv,:p_delimiter) from (select (column_value).getstringval() cv from xmltable(:v_in_str))'
     INTO v_res USING p_delimiter, v_in_str;
  --
  RETURN v_res;
  --
END;

--Test
SELECT remove_duplicate_elements('1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d"') AS res FROM dual
UNION ALL
SELECT remove_duplicate_elements('3 9 1 10 3 7 6 5 2 7 4 7 4 2 2 2 2 8 2 10 4 9 2 4 9 3 4 3 4 7',' ') AS res FROM dual
;


OPTION BASE 1
LET max = 10
DIM dat(10), res(10)
FOR i = 1 TO max
    READ dat(i)
NEXT i

DATA 1, 2, 1, 4, 5, 2, 15, 1, 3, 4

LET res(1) = dat(1)
LET count = 1
LET posic = 1
DO WHILE posic < max
   LET posic = posic + 1
   LET esnuevo = 1
   LET indice = 1
   DO WHILE (indice <= count) AND esnuevo = 1
      IF dat(posic) = res(indice) THEN LET esnuevo = 0
      LET indice = indice + 1
   LOOP
   IF esnuevo = 1 THEN
      LET count = count + 1
      LET res(count) = dat(posic)
   END IF
LOOP

FOR i = 1 TO count
    PRINT res(i);
NEXT i
END


//
// Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does.
//
INTEGER PROC FNBlockGetUniqueAllToBufferB( INTEGER bufferI )
 INTEGER B = FALSE
 INTEGER downB = TRUE
 STRING s[255] = ""
 IF ( NOT ( IsBlockInCurrFile() ) ) Warn( "Please mark a block" ) B = FALSE RETURN( B ) ENDIF // return from the current procedure if no block is marked
 PushPosition()
 PushBlock()
 GotoBlockBegin()
 WHILE ( ( IsCursorInBlock() ) AND ( downB ) )
  s = GetText( 1, MAXSTRINGLEN )
  PushPosition()
  PushBlock()
  GotoBufferId( bufferI )
  IF NOT LFind( s, "" )
   AddLine( s )
  ENDIF
  PopBlock()
  PopPosition()
  downB = Down()
 ENDWHILE
 PopPosition()
 PopBlock()
 B = TRUE
 RETURN( B )
END
//
PROC Main()
 INTEGER bufferI = 0
 PushPosition()
 bufferI = CreateTempBuffer()
 PopPosition()
 Message( FNBlockGetUniqueAllToBufferB( bufferI ) ) // gives e.g. TRUE
 GotoBufferId( bufferI )
END


$$ MODE TUSCRIPT
list_old="b'A'A'5'1'2'3'2'3'4"
list_sort=MIXED_SORT (list_old)
list_new=REDUCE (list_sort)
PRINT list_old
PRINT list_new


bash$ # original list
bash$ printf '6\n2\n3\n6\n4\n2\n'
6
2
3
6
4
2
bash$ # made uniq
bash$ printf '6\n2\n3\n6\n4\n2\n'|sort -n|uniq
2
3
4
6
bash$


Option Explicit

Sub Main()
Dim myArr() As Variant, i As Long

    myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235))
'return :
    For i = LBound(myArr) To UBound(myArr)
        Debug.Print myArr(i)
    Next
End Sub

Private Function Remove_Duplicate(Arr As Variant) As Variant()
Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long

    ReDim Temp(UBound(Arr))
    For i = LBound(Arr) To UBound(Arr)
        On Error Resume Next
        myColl.Add CStr(Arr(i)), CStr(Arr(i))
        If Err.Number > 0 Then
            On Error GoTo 0
        Else
            Temp(cpt) = Arr(i)
            cpt = cpt + 1
        End If
    Next i
    ReDim Preserve Temp(cpt - 1)
    Remove_Duplicate = Temp
End Function


Function remove_duplicates(list)
	arr = Split(list,",")
	Set dict = CreateObject("Scripting.Dictionary")
	For i = 0 To UBound(arr)
		If dict.Exists(arr(i)) = False Then
			dict.Add arr(i),""
		End If
	Next
	For Each key In dict.Keys
		tmp = tmp & key & ","
	Next
	remove_duplicates = Left(tmp,Len(tmp)-1)
End Function

WScript.Echo remove_duplicates("a,a,b,b,c,d,e,d,f,f,f,g,h")


Sort(0, File_Size)                                          // sort the data
While(Replace("^(.*)\N\1$", "\1", REGEXP+BEGIN+NOERR)){}    // remove duplicates


call filter(list, 'count(list, v:val) == 1')


LOCAL i As Integer, n As Integer, lcOut As String
CLOSE DATABASES ALL
CLEAR
CREATE CURSOR nums (num I)
INDEX ON num TAG num COLLATE "Machine"
SET ORDER TO 0
n = 50
RAND(-1)
FOR i = 1 TO n
    INSERT INTO nums VALUES (RanInt(1, 10))
ENDFOR
SELECT num, COUNT(num) As cnt FROM nums ;
GROUP BY num INTO CURSOR grouped
LIST OFF TO FILE grouped.txt NOCONSOLE
lcOut = ""
SCAN
    lcOut = lcOut + TRANSFORM(num) + ","
ENDSCAN
lcOut = LEFT(lcOut, LEN(lcOut)-1)
? lcOut

FUNCTION RanInt(tnLow As Integer, tnHigh As Integer) As Integer
RETURN INT((tnHigh - tnLow + 1)*RAND() + tnLow)
ENDFUNC


def (dedup l)
  let exists (table)
    collect+each x l
      unless exists.x
        yield x
      exists.x <- 1


import "/sort" for Sort

// Using a map - order of distinct items is undefined.
var removeDuplicates1 = Fn.new { |a|
    if (a.count <= 1) return a
    var m = {}
    for (e in a) m[e] = true
    return m.keys.toList
}

// Sort elements and remove consecutive duplicates.
var removeDuplicates2 = Fn.new { |a|
    if (a.count <= 1) return a
    Sort.insertion(a)
    for (i in a.count-1..1) {
        if (a[i] == a[i-1]) a.removeAt(i)
    }
    return a
}

// Iterate through list and for each element check if it occurs later in the list.
// If it does, discard it.
var removeDuplicates3 = Fn.new { |a|
    if (a.count <= 1) return a
    var i = 0
    while (i < a.count-1) {
        var j = i + 1
        while(j < a.count) {
            if (a[i] == a[j]) {
                a.removeAt(j)
            } else {
                j = j + 1
            }
        }
        i = i + 1
    }
    return a
}

var a = [1,2,3,4,1,2,3,5,1,2,3,4,5]
System.print("Original: %(a)")
System.print("Method 1: %(removeDuplicates1.call(a.toList))") // copy original each time
System.print("Method 2: %(removeDuplicates2.call(a.toList))")
System.print("Method 3: %(removeDuplicates3.call(a.toList))")


func RemoveDuplicates(Array){
	set NewArray = [];
	foreach(k,v as Array){
		if (NewArray->includes(v)){
			Array->splice(toint(k),1);
		} else {
			NewArray->push(v);
		}
	}
}

set Arr = ["Hello",1,2,"Hello",3,1];
log(Arr);
RemoveDuplicates(Arr);
log(Arr);


code Text=12;           \built-in routine to display a string of characters
string 0;               \use zero-terminated strings (not MSb terminated)

func StrLen(S);         \Return number of characters in an ASCIIZ string
char S;
int  I;
for I:= 0, -1>>1-1 do   \(limit = 2,147,483,646 if 32 bit, or 32766 if 16 bit)
        if S(I) = 0 then return I;

func Unique(S);         \Remove duplicate bytes from string
char S;
int  I, J, K, L;
[L:= StrLen(S);                         \string length
for I:= 0 to L-1 do                     \for all characters in string...
    for J:= I+1 to L-1 do               \scan rest of string for duplicates
        if S(I) = S(J) then             \if duplicate then
            [for K:= J+1 to L do        \ shift rest of string down (including
                S(K-1):= S(K);          \ terminating zero)
            L:= L-1                     \ string is now one character shorter
            ];
return S;                               \return pointer to string
];

Text(0, Unique("Pack my box with five dozen liquor jugs."))


data "Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "the", "party.", ""

do
    read p$
    if p$ = "" break
    if not instr(r$, p$) r$ = r$ + p$ + " "
loop

print r$


program: remove_duplicate_elements
  input: [1,2,1,3,2,4,1]
  output: [1,2,3,4]


name := "sample"
waitsec := 5
Tooltip Recording %name%.wav
MCI_SendString("close all wait")
MCI_SendString("open new type waveaudio alias " . name)
MCI_SendString("set " . name . " time format ms wait")
;MCI_SendString("set " . name . " bitspersample 16 wait")
;MCI_SendString("set " . name . " channels 1 wait")
;MCI_SendString("set " . name . " samplespersec 16000 wait")
;MCI_SendString("set " . name . " alignment 1 wait")
;MCI_SendString("set " . name . " bytespersec 8000 wait")
MCI_SendString("record " . name)
Sleep waitsec*1000
MCI_SendString("stop " . name . " wait")
MCI_SendString("save " . name . " """ . name . ".wav""")
Tooltip Finished ... Playing
MCI_SendString("delete " . name)
MCI_SendString("close " . name . " wait")
MCI_SendString("open """ . name . ".wav"" type waveaudio alias " . name)
MCI_SendString("play " . name . " wait")
MCI_SendString("close " . name . " wait")
Tooltip
Return

MCI_SendString(p_lpszCommand,ByRef r_lpszReturnString="",p_hwndCallback=0) {
	VarSetCapacity(r_lpszReturnString,512,0)
	Return DllCall("winmm.dll\mciSendString" . (A_IsUnicode ? "W":"A")
		,"Str",p_lpszCommand						;-- lpszCommand
		,"Str",r_lpszReturnString					;-- lpszReturnString
		,"UInt",512									;-- cchReturn
		,A_PtrSize ? "Ptr":"UInt",p_hwndCallback	;-- hwndCallback
		,"Cdecl Int")								;-- Return type
}
; For more intuitive functions, see the MCI library by jballi.
; doc: http://www.autohotkey.net/~jballi/MCI/v1.1/MCI.html
; download: http://www.autohotkey.net/~jballi/MCI/v1.1/MCI.ahk


      wavfile$ = @dir$ + "capture.wav"
      bitspersample% = 16
      channels% = 2
      samplespersec% = 44100

      alignment% = bitspersample% * channels% / 8
      bytespersec% = alignment% * samplespersec%

      params$ = " bitspersample " + STR$(bitspersample%) + \
      \         " channels " + STR$(channels%) + \
      \         " alignment " + STR$(alignment%) + \
      \         " samplespersec " + STR$(samplespersec%) + \
      \         " bytespersec " + STR$(bytespersec%)

      SYS "mciSendString", "close all", 0, 0, 0
      SYS "mciSendString", "open new type waveaudio alias capture", 0, 0, 0
      SYS "mciSendString", "set capture" + params$, 0, 0, 0 TO res%
      IF res% ERROR 100, "Couldn't set capture parameters: " + STR$(res% AND &FFFF)

      PRINT "Press SPACE to start recording..."
      REPEAT UNTIL INKEY(1) = 32

      SYS "mciSendString", "record capture", 0, 0, 0 TO res%
      IF res% ERROR 100, "Couldn't start audio capture: " + STR$(res% AND &FFFF)

      PRINT "Recording, press SPACE to stop..."
      REPEAT UNTIL INKEY(1) = 32

      SYS "mciSendString", "stop capture", 0, 0, 0
      SYS "mciSendString", "save capture " + wavfile$, 0, 0, 0 TO res%
      IF res% ERROR 100, "Couldn't save to WAV file: " + STR$(res% AND &FFFF)

      SYS "mciSendString", "delete capture", 0, 0, 0
      SYS "mciSendString", "close capture", 0, 0, 0

      PRINT "Captured audio is stored in " wavfile$


#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

void * record(size_t bytes)
{
	int fd;
	if (-1 == (fd = open("/dev/dsp", O_RDONLY))) return 0;
	void *a = malloc(bytes);
	read(fd, a, bytes);
	close(fd);
	return a;
}

int play(void *buf, size_t len)
{
	int fd;
	if (-1 == (fd = open("/dev/dsp", O_WRONLY))) return 0;
	write(fd, buf, len);
	close(fd);
	return 1;
}

int main()
{
	void *p = record(65536);
	play(p, 65536);
	return 0;
}


#include <iostream>
#include <string>
#include <windows.h>
#include <mmsystem.h>

#pragma comment ( lib, "winmm.lib" )
using namespace std;

class recorder
{
public:
    void start()
    {
	paused = rec = false; action = "IDLE";
	while( true )
	{
	    cout << endl << "==" << action << "==" << endl << endl;
	    cout << "1) Record" << endl << "2) Play" << endl << "3) Pause" << endl << "4) Stop" << endl << "5) Quit" << endl;
	    char c; cin >> c;
	    if( c > '0' && c < '6' )
	    {
		switch( c )
		{
		    case '1': record(); break;
		    case '2': play();   break;
		    case '3': pause();  break;
		    case '4': stop();   break;
		    case '5': stop();   return;
		}
	    }
	}
    }
private:
    void record()
    {
	if( mciExecute( "open new type waveaudio alias my_sound") )
	{
	    mciExecute( "record my_sound" );
	    action = "RECORDING"; rec = true;
	}
    }
    void play()
    {
	if( paused )
	    mciExecute( "play my_sound" );
	else
	    if( mciExecute( "open tmp.wav alias my_sound" ) )
		mciExecute( "play my_sound" );

	action = "PLAYING";
	paused = false;
    }
    void pause()
    {
	if( rec ) return;
	mciExecute( "pause my_sound" );
	paused = true; action = "PAUSED";
    }
    void stop()
    {
	if( rec )
	{
	    mciExecute( "stop my_sound" );
	    mciExecute( "save my_sound tmp.wav" );
	    mciExecute( "close my_sound" );
	    action = "IDLE"; rec = false;
	}
	else
	{
	    mciExecute( "stop my_sound" );
	    mciExecute( "close my_sound" );
	    action = "IDLE";
	}
    }
    bool mciExecute( string cmd )
    {
	if( mciSendString( cmd.c_str(), NULL, 0, NULL ) )
	{
	    cout << "Can't do this: " << cmd << endl;
	    return false;
	}
	return true;
    }

    bool paused, rec;
    string action;
};

int main( int argc, char* argv[] )
{
    recorder r; r.start();
    return 0;
}


// chuck this with other shreds to record to file
// example> chuck foo.ck bar.ck rec

// arguments: rec:<filename>

// get name
me.arg(0) => string filename;
if( filename.length() == 0 ) "foo.wav" => filename;

// pull samples from the dac
dac => Gain g => WvOut w => blackhole;
// this is the output file name
filename => w.wavFilename;
<<<"writing to file:", "'" + w.filename() + "'">>>;
// any gain you want for the output
.5 => g.gain;

// temporary workaround to automatically close file on remove-shred
null @=> w;

// infinite time loop...
// ctrl-c will stop it, or modify to desired duration
while( true ) 1::second => now;


(defun record (n)
  (with-open-file (in "/dev/dsp" :element-type '(unsigned-byte 8))
    (loop repeat n collect (read-byte in))
    )
  )
(defun play (byte-list)
  (with-open-file (out "/dev/dsp" :direction :output :element-type '(unsigned-byte 8) :if-exists :append)
    (mapcar (lambda (b) (write-byte b out)) byte-list)
    )
  )
(play (record 65536))


package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "os/exec"
    "strconv"
)

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    name := ""
    for name == "" {
        fmt.Print("Enter output file name (without extension) : ")
        scanner.Scan()
        name = scanner.Text()
        check(scanner.Err())
    }
    name += ".wav"

    rate := 0
    for rate < 2000 || rate > 192000 {
        fmt.Print("Enter sampling rate in Hz (2000 to 192000) : ")
        scanner.Scan()
        input := scanner.Text()
        check(scanner.Err())
        rate, _ = strconv.Atoi(input)
    }
    rateS := strconv.Itoa(rate)

    dur := 0.0
    for dur < 5 || dur > 30 {
        fmt.Print("Enter duration in seconds (5 to 30)        : ")
        scanner.Scan()
        input := scanner.Text()
        check(scanner.Err())
        dur, _ = strconv.ParseFloat(input, 64)
    }
    durS := strconv.FormatFloat(dur, 'f', -1, 64)

    fmt.Println("OK, start speaking now...")
    // Default arguments: -c 1, -t wav. Note only signed 16 bit format supported.
    args := []string{"-r", rateS, "-f", "S16_LE", "-d", durS, name}
    cmd := exec.Command("arecord", args...)
    err := cmd.Run()
    check(err)

    fmt.Printf("'%s' created on disk and will now be played back...\n", name)
    cmd = exec.Command("aplay", name)
    err = cmd.Run()
    check(err)
    fmt.Println("Play-back completed.")
}


begin_funct({wav}, Record sound);
    set_decision(linger);
    find_thing()_first()_microphone()_bitrate(16)_tech(PCM)_samplerate(signed16, unsigned16)_rangefrom(8000, Hz)_rangeto(44100, Hz)_export(.wav)
        ? with_found()_microphone()_label(mic);
        : err_funct[]_err(Sorry, no one has a microphone!);
          exit_funct[];
    ;
    with_microphone[mic]_record()_durat({secs}, 30)_var(recording);
    [Record sound]_ret([recording]);
    reset_decision();
end_funct[];

// Record a monophonic 16-bit PCM sound into memory space:
exec_funct(Record sound)_var(PCMRecording)_me();         // The variable 'PCMRecording' is the sound in memory space

// Record a monophonic 16-bit PCM sound into a file or array:
exec_funct(Record sound)_file(foo.wav)_me();         // The file 'foo.wav' is the sound in a file


using PortAudio, LibSndFile

stream = PortAudioStream("Microphone (USB Microphone)", 1, 0) # 44100 samples/sec
buf = read(stream, 441000)
save("recorded10sec.wav", buf)


// version 1.1.3

import java.io.File
import javax.sound.sampled.*

const val RECORD_TIME = 20000L // twenty seconds say

fun main(args: Array<String>) {
    val wavFile = File("RecordAudio.wav")
    val fileType = AudioFileFormat.Type.WAVE
    val format = AudioFormat(16000.0f, 16, 2, true, true)
    val info = DataLine.Info(TargetDataLine::class.java, format)
    val line = AudioSystem.getLine(info) as TargetDataLine

    // Creates a new thread that waits for 'RECORD_TIME' before stopping
    Thread(object: Runnable {
        override fun run() {
            try {
                Thread.sleep(RECORD_TIME)
            }
            catch (ie: InterruptedException) {
                println(ie.message)
            }
            finally {
                line.stop()
                line.close()
            }
            println("Finished")
         }
    }).start()

    // Captures the sound and saves it in a WAV file
    try {
        if (AudioSystem.isLineSupported(info)) {
            line.open(format)
            line.start()
            println("Recording started")
            AudioSystem.write(AudioInputStream(line), fileType, wavFile)
        }
        else println("Line not supported")
    }
    catch (lue: LineUnavailableException) {
        println(lue.message)
    }
}


command makeRecording
    set the dontUseQT to false -- on windows use true
    set the recordFormat to "wave" -- can be wav,aiff, au
    set the recordRate to 44.1 -- sample at 44100 Hz
    set the recordSampleSize to 16  --default is 8 bit
    ask file "Save recording as"
    if it is not empty then
        answer record --show sound input dialog with presets above
        record sound file it  -- actual record command
        wait 10 seconds
        stop recording
    end if
end makeRecording


import osproc, strutils

var name = ""
while name.len == 0:
  stdout.write "Enter output file name (without extension): "
  name = stdin.readLine().strip()
name.add ".wav"

var rate = 0
while rate notin 2000..19_200:
  stdout.write "Enter sampling rate in Hz (2000 to 192000): "
  try: rate = parseInt(stdin.readLine().strip())
  except ValueError: discard

var duration = 0
while duration notin 5..30:
  stdout.write "Enter duration in seconds (5 to 30): "
  try: duration = parseInt(stdin.readLine().strip())
  except ValueError: discard

echo "OK, start speaking now..."
# Default arguments: -c 1, -t wav. Note that only signed 16 bit format is supported.
let args = ["-r", $rate, "-f", "S16_LE", "-d", $duration, name]
echo execProcess("arecord", args = args, options = {poStdErrToStdOut, poUsePath})

echo "'$1' created on disk and will now be played back..." % name
echo execProcess("aplay", args = [name], options = {poStdErrToStdOut, poUsePath})
echo "Playback completed"


#load "unix.cma"

let record bytes =
  let buf = String.make bytes '\000' in
  let ic = open_in "/dev/dsp" in
  let chunk = 4096 in
  for i = 0 to pred (bytes / chunk) do
    ignore (input ic buf (i * chunk) chunk)
  done;
  close_in ic;
  (buf)

let play buf len =
  let oc = open_out "/dev/dsp" in
  output_string oc buf;
  close_out oc

let () =
  let bytes = 65536 in
  let p = record bytes in
  play p bytes


--
-- demo\rosetta\Record_sound.exw
-- =============================
--
without js -- (file i/o)
constant wavfile = "capture.wav",
         bitspersample = 16,
         channels = 2,
         samplespersec = 44100,
         alignment = bitspersample * channels / 8,
         bytespersec = alignment * samplespersec,
         params = sprintf(" bitspersample %d channels %d alignment %d samplespersec %d bytespersec %d",
                           {bitspersample,   channels,   alignment,   samplespersec,   bytespersec}),
         error_size = 2048
atom winmm = NULL, xmciSendString, pError

procedure mciSendString(string msg)
    if winmm=NULL then
         winmm = open_dll("winmm.dll")
         xmciSendString = define_c_func(winmm,"mciSendStringA",
            {C_PTR,     --  LPCTSTR lpszCommand
             C_PTR,     --  LPTSTR lpszReturnString
             C_INT,     --  UINT cchReturn
             C_PTR},    --  HANDLE hwndCallback
            C_INT)      -- MCIERROR
         pError = allocate(error_size)
    end if
    atom res = c_func(xmciSendString,{msg,pError,error_size,NULL})
    if res!=0 then crash("error %0x: %s",{res,peek_string(pError)}) end if
end procedure

include get.e   -- get_bytes()

function record(integer bytes)
    integer fn = open("/dev/dsp","rb")
    if fn=-1 then return "" end if
    string res = get_bytes(fn,bytes)
    close(fn)
    return res
end function

procedure play(string buf)
    if length(buf) then
        integer fn = open("/dev/dsp","wb")
        if fn!=-1 then
            puts(fn,buf)
            close(fn)
        end if
    end if
end procedure

if platform()=WINDOWS then
    mciSendString("close all")
    mciSendString("open new type waveaudio alias capture")
    mciSendString("set capture" & params)

    puts(1,"Press SPACE to start recording...")
    while wait_key()!=' ' do end while

    mciSendString("record capture")
    puts(1,"Recording, press SPACE to stop...")
    while wait_key()!=' ' do end while

    mciSendString("stop capture")
    mciSendString("save capture " & wavfile)
    mciSendString("delete capture")
    mciSendString("close capture")

    puts(1,"Captured audio is stored in "&wavfile)
elsif platform()=LINUX then
    -- warning: untested
    play(record(65536))
--  -- alternative, from Go (ditto)
--  string name = "test.wav",
--         rate = "2000", -- (2000..192000 Hz)
--         durn = "5" -- (5 to 30 seconds)
--  printf(1,"OK, start speaking now...\n")
--  -- Default arguments: -c 1, -t wav. Note only signed 16 bit format supported.
--  string cmd = sprintf("arecord -r %s -f S16_LE -d %s %s", {rate,durn,name})
--  {} = system_exec(cmd)
--  printf(1,"'%s' created on disk and will now be played back...\n", {name})
--  {} = system_exec("aplay "&name)
--  printf(1,"Play-back completed.\n")
end if


(in '(rec -q -c1 -tu16 - trim 0 2)  # Record 2 seconds
   (make
      (while (rd 2)
         (link @) ) ) )


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) for i in data]


#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))


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, :$format, :w);
    my $st;

    if $source.defined {
        my $index = 0;
        for $pa.devices -> $device {
            if $device.name eq $source {
                else {
                    my $la = $device.default-high-input-latency;
                    my $si = Audio::PortAudio::StreamParameters.new(device => $index,
                                                                    channel-count => 1,
                                                                    sample-format => Audio::PortAudio::StreamFormat::Float32,
                                                                    suggested-latency => ($la || 0.05e0 ));
                    $st = $pa.open-stream($si, Audio::PortAudio::StreamParameters, 44100, $buffer );
                    last;
                }

            }
            $index++;
        }
        die "Couldn't find a device for '$source'" if !$st.defined;
    }
    else {
        $st = $pa.open-default-stream(2,0, Audio::PortAudio::StreamFormat::Float32, 44100, $buffer);
    }
    $st.start;
    my $p = Promise.new;
    signal(SIGINT).act({
        say "stopping recording";
        $p.keep: "stopped";
        $out-file.close;
        $st.close;
        exit;
    });
    my Channel $write-channel = Channel.new;
    my $write-promise = start {
        react {
            whenever $write-channel -> $item {
                if $p.status ~~ Planned {
                    $out-file.write-float($item[0], $item[1]);
                    $out-file.sync;
                }
                else {
                    done;
                }
            }
        }
    };

    loop {
        if $p.status ~~ Planned {
            my $f = $buffer || $st.read-available;
            if $f > 0 {
                my $buff = $st.read($f,2, num32);
                $write-channel.send([$buff, $f]);
            }
        }
        else {
            last;
        }
    }

}


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 minute

  // path and format of the wav file
  val (wavFile, fileType) = (new File("RecordAudio.wav"), AudioFileFormat.Type.WAVE)
  val format = new AudioFormat(/*sampleRate =*/ 16000f,
    /*sampleSizeInBits =*/ 16,
    /*channels =*/ 2,
    /*signed =*/ true,
    /*bigEndian =*/ true)

  val info = new DataLine.Info(classOf[TargetDataLine], format)
  val line: TargetDataLine = AudioSystem.getLine(info).asInstanceOf[TargetDataLine]

  // Entry to run the program

  // Creates a new thread that waits for a specified of time before stopping
  new Thread(new Runnable() {
    def run() {
      try {
        Thread.sleep(RECORD_TIME)
      } catch {
        case ex: InterruptedException => ex.printStackTrace()
      }
      finally {
        line.stop()
        line.close()
      }
      println("Finished")
    }
  }).start()

  //Captures the sound and record into a WAV file
  try {
    // checks if system supports the data line
    if (AudioSystem.isLineSupported(info)) {
      line.open(format)
      line.start() // start capturing
      println("Recording started")
      AudioSystem.write(new AudioInputStream(line), fileType, wavFile)
    } else println("Line not supported")
  } catch {
    case ex: LineUnavailableException => ex.printStackTrace()
    case ioe: IOException => ioe.printStackTrace()
  }
}


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 true
delay 1000
$recording stop

# Convert the internal buffer to viewable numbers, and print them out
binary scan [$recording data -byteorder littleEndian] s* words
puts [join $words ", "]

# Destroy the recording object
$recording destroy


print 1 "Recording..."
micrec
print 1 "Playing..."
micpla
end


/* 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 (!rate || !rate.isInteger || rate < 2000 || rate > 192000) {
    System.write("Enter sampling rate in Hz (2000 to 192000) : ")
    rate = Num.fromString(C.getInput(6))
}
var rateS = rate.toString

var dur = 0
while (!dur || dur < 5 || dur > 30) {
    System.write("Enter duration in seconds (5 to 30)        : ")
    dur = Num.fromString(C.getInput(5))
}
var durS = dur.toString

System.print("\nOK, start speaking now...")
// Default arguments: -c 1, -t wav. Note only signed 16 bit format supported.
var args = ["-r", rateS, "-f", "S16_LE", "-d", durS, name]
C.arecord(args.join(" "))

System.print("\n'%(name)' created on disk and will now be played back...")
C.aplay(name)
System.print("\nPlay-back completed.")


V string = ‘This is a string’

I re:‘string$’.search(string)
   print(‘Ends with string.’)

string = string.replace(re:‘ a ’, ‘ another ’)
print(string)


"haystack" /a./ r:match . cr
"haystack" /a./ "blah" s:replace! . cr


DATA: text TYPE string VALUE 'This is a Test'.

FIND FIRST OCCURRENCE OF REGEX 'is' IN text.
IF sy-subrc = 0.
  cl_demo_output=>write( 'Regex matched' ).
ENDIF.

REPLACE ALL OCCURRENCES OF REGEX '[t|T]est' IN text WITH 'Regex'.

cl_demo_output=>write( text ).
cl_demo_output=>display( ).


with Ada.Text_IO; with Gnat.Regpat; use Ada.Text_IO;

procedure Regex is

   package Pat renames Gnat.Regpat;

   procedure Search_For_Pattern(Compiled_Expression: Pat.Pattern_Matcher;
                                Search_In: String;
                                First, Last: out Positive;
                                Found: out Boolean) is
      Result: Pat.Match_Array (0 .. 1);
   begin
      Pat.Match(Compiled_Expression, Search_In, Result);
      Found := not Pat."="(Result(1), Pat.No_Match);
      if Found then
         First := Result(1).First;
         Last := Result(1).Last;
      end if;
   end Search_For_Pattern;

   Word_Pattern: constant String := "([a-zA-Z]+)";

   Str:           String:= "I love PATTERN matching!";
   Current_First: Positive := Str'First;
   First, Last:   Positive;
   Found:         Boolean;

begin
   -- first, find all the words in Str
   loop
      Search_For_Pattern(Pat.Compile(Word_Pattern),
                         Str(Current_First .. Str'Last),
                         First, Last, Found);
   exit when not Found;
      Put_Line("<" & Str(First .. Last) & ">");
      Current_First := Last+1;
   end loop;

   -- second, replace "PATTERN" in Str by "pattern"
   Search_For_Pattern(Pat.Compile("(PATTERN)"), Str, First, Last, Found);
   Str := Str(Str'First .. First-1) & "pattern" & Str(Last+1 .. Str'Last);
   Put_Line(Str);
end Regex;


INT match=0, no match=1, out of memory error=2, other error=3;

STRING str := "i am a string";

# Match: #

STRING m := "string$";
INT start, end;
IF grep in string(m, str, start, end) = match THEN printf(($"Ends with """g""""l$, str[start:end])) FI;

# Replace: #

IF sub in string(" a ", " another ",str) = match THEN printf(($gl$, str)) FI;


#include <hopper.h>

main:
   expReg="[A-Z]{1,2}[0-9][0-9A-Z]? +[0-9][A-Z]{2}"
   flag compile = REG_EXTENDED
   flag match=0
   número de matches=10, T1=0

   {flag compile,expReg} reg compile(T1)  // compile regular expression, pointed whit T1
   {flag match,número de matches,T1,"We are at SN12 7NY for this course"},reg match, // execute
   println
   reg free(T1)   // free pointer to regular expression compiled.

exit(0)


try
    find text ".*string$" in "I am a string" with regexp
on error message
    return message
end try

try
    change "original" into "modified" in "I am the original string" with regexp
on error message
    return message
end try


use std, regex

(: matching :)
if "some matchable string" =~ /^some" "+[a-z]*" "+string$/
  echo string matches
else
  echo string "doesn't" match

(: replacing :)
let t = strdup "some allocated string"
t =~ s/a/"4"/g
t =~ s/e/"3"/g
t =~ s/i/"1"/g
t =~ s/o/"0"/g
t =~ s/s/$/g
print t
free t

(: flushing regex allocations :)
uninit regex

check mem leak; use dbg (:optional:)


s: "This is a string"

if contains? s {/string$/} -> print "yes, it ends with 'string'"

replace 's {/[as]/} "x"

print s


MsgBox % foundpos := RegExMatch("Hello World", "World$")
MsgBox % replaced := RegExReplace("Hello World", "World$", "yourself")


$ awk '{if($0~/[A-Z]/)print "uppercase detected"}'
abc
ABC
uppercase detected


      SYS "LoadLibrary", "gnu_regex.dll" TO gnu_regex%
      IF gnu_regex% = 0 ERROR 100, "Cannot load gnu_regex.dll"
      SYS "GetProcAddress", gnu_regex%, "regcomp" TO regcomp
      SYS "GetProcAddress", gnu_regex%, "regexec" TO regexec

      DIM regmatch{start%, finish%}, buffer% 256

      REM Find all 'words' in a string:
      teststr$ = "I love PATTERN matching!"
      pattern$ = "([a-zA-Z]+)"

      SYS regcomp, buffer%, pattern$, 1 TO result%
      IF result% ERROR 101, "Failed to compile regular expression"

      first% = 1
      REPEAT
        SYS regexec, buffer%, MID$(teststr$, first%), 1, regmatch{}, 0 TO result%
        IF result% = 0 THEN
          s% = regmatch.start%
          f% = regmatch.finish%
          PRINT "<" MID$(teststr$, first%+s%, f%-s%) ">"
          first% += f%
        ENDIF
      UNTIL result%

      REM Replace 'PATTERN' with 'pattern':
      teststr$ = "I love PATTERN matching!"
      pattern$ = "(PATTERN)"

      SYS regcomp, buffer%, pattern$, 1 TO result%
      IF result% ERROR 101, "Failed to compile regular expression"
      SYS regexec, buffer%, teststr$, 1, regmatch{}, 0 TO result%
      IF result% = 0 THEN
        s% = regmatch.start%
        f% = regmatch.finish%
        MID$(teststr$, s%+1, f%-s%) = "pattern"
        PRINT teststr$
      ENDIF

      SYS "FreeLibrary", gnu_regex%


str = "I am a string"

true? str.match(/string$/)
 { p "Ends with 'string'" }

false? str.match(/^You/)
 { p "Does not start with 'You'" }


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>
#include <string.h>

int main()
{
   regex_t preg;
   regmatch_t substmatch[1];
   const char *tp = "string$";
   const char *t1 = "this is a matching string";
   const char *t2 = "this is not a matching string!";
   const char *ss = "istyfied";

   regcomp(&preg, "string$", REG_EXTENDED);
   printf("'%s' %smatched with '%s'\n", t1,
                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp);
   printf("'%s' %smatched with '%s'\n", t2,
                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp);
   regfree(&preg);
   /* change "a[a-z]+" into "istifyed"?*/
   regcomp(&preg, "a[a-z]+", REG_EXTENDED);
   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )
   {
      //fprintf(stderr, "%d, %d\n", substmatch[0].rm_so, substmatch[0].rm_eo);
      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +
                        (strlen(t1) - substmatch[0].rm_eo) + 2);
      memcpy(ns, t1, substmatch[0].rm_so+1);
      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));
      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],
                strlen(&t1[substmatch[0].rm_eo]));
      ns[ substmatch[0].rm_so + strlen(ss) +
          strlen(&t1[substmatch[0].rm_eo]) ] = 0;
      printf("mod string: '%s'\n", ns);
      free(ns);
   } else {
      printf("the string '%s' is the same: no matching!\n", t1);
   }
   regfree(&preg);

   return 0;
}


using System;
using System.Text.RegularExpressions;

class Program {
    static void Main(string[] args) {
        string str = "I am a string";

        if (new Regex("string$").IsMatch(str)) {
            Console.WriteLine("Ends with string.");
        }

        str = new Regex(" a ").Replace(str, " another ");
        Console.WriteLine(str);
    }
}


#include <iostream>
#include <string>
#include <iterator>
#include <regex>

int main()
{
  std::regex re(".* string$");
  std::string s = "Hi, I am a string";

  // match the complete string
  if (std::regex_match(s, re))
    std::cout << "The string matches.\n";
  else
    std::cout << "Oops - not found?\n";

  // match a substring
  std::regex re2(" a.*a");
  std::smatch match;
  if (std::regex_search(s, match, re2))
  {
    std::cout << "Matched " << match.length()
              << " characters starting at " << match.position() << ".\n";
    std::cout << "Matched character sequence: \""
              << match.str() << "\"\n";
  }
  else
  {
    std::cout << "Oops - not found?\n";
  }

  // replace a substring
  std::string dest_string;
  std::regex_replace(std::back_inserter(dest_string),
                       s.begin(), s.end(),
                       re2,
                       "'m now a changed");
  std::cout << dest_string << std::endl;
}


proc MAIN()
  char array STRING
  open (1,"D:FILE.TXT",4,0)
  inputsd(1,STRING)
  close(1)
return


with Ada.Directories,
     Ada.Direct_IO,
     Ada.Text_IO;

procedure Whole_File is

   File_Name : String  := "whole_file.adb";
   File_Size : Natural := Natural (Ada.Directories.Size (File_Name));

   subtype File_String    is String (1 .. File_Size);
   package File_String_IO is new Ada.Direct_IO (File_String);

   File     : File_String_IO.File_Type;
   Contents : File_String;

begin
   File_String_IO.Open  (File, Mode => File_String_IO.In_File,
                               Name => File_Name);
   File_String_IO.Read  (File, Item => Contents);
   File_String_IO.Close (File);

   Ada.Text_IO.Put (Contents);
end Whole_File;


MODE BOOK = FLEX[0]FLEX[0]FLEX[0]CHAR; ¢ pages of lines of characters ¢
BOOK book;

FILE book file;
INT errno = open(book file, "book.txt", stand in channel);

get(book file, book)


(let [s "I am a string"]
  ;; match
  (when (re-find #"string$" s)
    (println "Ends with 'string'."))
  (when-not (re-find #"^You" s)
    (println "Does not start with 'You'."))

  ;; substitute
  (println (clojure.string/replace s " a " " another "))
)


(let ((string "I am a string"))
  (when (cl-ppcre:scan "string$" string)
    (write-line "Ends with string"))
  (unless (cl-ppcre:scan "^You" string )
    (write-line "Does not start with 'You'")))


void main() {
    import std.stdio, std.regex;

    immutable s = "I am a string";

    // Test.
    if (s.match("string$"))
        "Ends with 'string'.".writeln;

    // Substitute.
    s.replace(" a ".regex, " another ").writeln;
}


#include <hopper.h>

main:
   s=""
   load str ("archivo.txt") (s)
   println ( "File loaded:\n",s )
exit(0)


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 access fileRef


val s = fileref_get_file_string (stdin_ref)


RegExp regexp = new RegExp(r'\w+\!');

String capitalize(Match m) => '${m[0].substring(0, m[0].length-1).toUpperCase()}';

void main(){
  String hello = 'hello hello! world world!';
  String hellomodified = hello.replaceAllMapped(regexp, capitalize);
  print(hello);
  print(hellomodified);
}


program Regular_expressions;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils,
  System.RegularExpressions;

const
  CPP_IF = '\s*if\s*\(\s*(?<COND>.*)\s*\)\s*\{\s*return\s+(?<RETURN>.+);\s*\}';
  PASCAL_IF = 'If ${COND} then result:= ${RETURN};';

var
  RegularExpression: TRegEx;
  str: string;

begin
  str := ' if ( a < 0 ) { return -a; }';

  Writeln('Expression: '#10#10, str);

  if RegularExpression.Create(CPP_IF).IsMatch(str) then
  begin
    Writeln(#10'   Is a single If in Cpp:'#10);

    Writeln('Translate to Pascal:'#10);
    str := RegularExpression.Create(CPP_IF).Replace(str, PASCAL_IF);
    Writeln(str);
  end;
  readln;
end.


str = "This is a string"
if str =~ ~r/string$/, do: IO.inspect "str ends with 'string'"


fileread, varname, C:\filename.txt ; adding "MsgBox %varname%" (no quotes) to the next line will display the file contents.


$fileOpen = FileOpen("file.txt")
$fileRead = FileRead($fileOpen)
FileClose($fileOpen)


#!/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;
}


(let ((string "I am a string"))
  (when (string-match-p "string$" string)
    (message "Ends with 'string'"))
  (message "%s" (replace-regexp-in-string " a " " another " string)))


match() ->
	String = "This is a string",
	case re:run(String, "string$") of
		{match,_} -> io:format("Ends with 'string'~n");
		_ -> ok
	end.

substitute() ->
	String = "This is a string",
	NewString = re:replace(String, " a ", " another ", [{return, list}]),
	io:format("~s~n",[NewString]).


DIM f AS STRING
OPEN "file.txt" FOR BINARY AS 1
f = SPACE$(LOF(1))
GET #1, 1, f
CLOSE 1


      file% = OPENIN("input.txt")
      strvar$ = ""
      WHILE NOT EOF#file%
        strvar$ += CHR$(BGET#file%)
      ENDWHILE
      CLOSE #file%


global _start

: syscall ( num:eax -- result:eax ) syscall ;

: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;
: die ( err:eax -- noret ) neg exit ;

: unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ;
: ordie ( result -- ) unwrap drop ;

: open ( pathname:edi flags:esi -- fd:eax ) 2 syscall unwrap ;
: close ( fd:edi -- ) 3 syscall ordie ;

48 resb stat_buf
8 resb file-size
88 resb padding

: fstat ( fd:edi buf:esi -- ) 5 syscall ordie ;

1 const prot_read
2 const map_private

: mmap ( fd:r8d len:esi addr:edi off:r9d prot:edx flags:r10d -- buf:eax ) 9 syscall unwrap ;
: munmap ( addr:edi len:esi -- ) 11 syscall ordie ;

1 resd fd
0 const read-only

: open-file ( pathname:edi -- ) read-only open fd ! ;
: read-file-size ( -- ) fd @ stat_buf fstat ;
: map-file ( fd len -- buf ) 0 0 prot_read map_private mmap ;
: map-file ( -- buf ) fd @ file-size @ map-file ;
: unmap-file ( buf -- ) file-size @ munmap ;
: close-file ( -- ) fd @ close ;

: open-this-file ( -- ) s" read_entire_file.blue" drop open-file ;

: _start ( -- noret )
	open-this-file
	read-file-size
	map-file
	\ do something ...
	unmap-file
	close-file
	bye
;


•file.Chars "file"
•file.Bytes "file"

# Shorthands:
•FChars "file"
•FBytes "file"


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


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


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]
  .( String matches with the expression.) cr
[ELSE]
  .( No match.) cr
[THEN]


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


>     Keep cell 0 at 0 as a sentinel value
,[>,] Read into successive cells until EOF
<[<]  Go all the way back to the beginning
>[.>] Print successive cells while nonzero


#include <stdio.h>
#include <stdlib.h>

int main()
{
  char *buffer;
  FILE *fh = fopen("readentirefile.c", "rb");
  if ( fh != NULL )
  {
    fseek(fh, 0L, SEEK_END);
    long s = ftell(fh);
    rewind(fh);
    buffer = malloc(s);
    if ( buffer != NULL )
    {
      fread(buffer, s, 1, fh);
      // we can now close the file
      fclose(fh); fh = NULL;

      // do something, e.g.
      fwrite(buffer, s, 1, stdout);

      free(buffer);
    }
    if (fh != NULL) fclose(fh);
  }
  return EXIT_SUCCESS;
}


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"]
}


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


&string = &string.ReplaceRegEx("^\s+|\s+$", "") // it's a trim!
&string = &string.ReplaceRegEx("Another (Match)", "Replacing $1") // Using replace groups


using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var fileContents = File.ReadAllText("c:\\autoexec.bat");
        // Can optionally take a second parameter to specify the encoding, e.g. File.ReadAllText("c:\\autoexec.bat", Encoding.UTF8)
    }
}


#include <iostream>
#include <fstream>
#include <string>
#include <iterator>

int main( )
{
    if (std::ifstream infile("sample.txt"))
    {
        // construct string from iterator range
        std::string fileData(std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>());

        cout << "File has " << fileData.size() << "chars\n";

        // don't need to manually close the ifstream; it will release the file when it goes out of scope
        return 0;
   }
   else
   {
      std::cout << "file not found!\n";
      return 1;
   }
}


(slurp "myfile.txt")
(slurp "my-utf8-file.txt" "UTF-8")


[indent=4]
/* Regular expressions, in Genie */

init
    var sentence = "This is a sample sentence."
    try
        var re = new Regex("s[ai]mple")

        if re.match(sentence)
            print "matched '%s' in '%s'", re.get_pattern(), sentence

        var offs = 0
        print("replace with 'different': %s",
            re.replace(sentence, sentence.length, offs, "different"))

    except err:RegexError
        print err.message


package main
import "fmt"
import "regexp"

func main() {
  str := "I am the original string"

  // Test
  matched, _ := regexp.MatchString(".*string$", str)
  if matched { fmt.Println("ends with 'string'") }

  // Substitute
  pattern := regexp.MustCompile("original")
  result := pattern.ReplaceAllString(str, "modified")
  fmt.Println(result)
}


import java.util.regex.*;

def woodchuck = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
def pepper = "Peter Piper picked a peck of pickled peppers"

println "=== Regular-expression String syntax (/string/) ==="
def woodRE = /[Ww]o\w+d/
def piperRE = /[Pp]\w+r/
assert woodRE instanceof String && piperRE instanceof String
assert (/[Ww]o\w+d/ == "[Ww]o\\w+d") && (/[Pp]\w+r/ == "[Pp]\\w+r")
println ([woodRE: woodRE, piperRE: piperRE])
println ()

println "=== Pattern (~) operator ==="
def woodPat = ~/[Ww]o\w+d/
def piperPat = ~piperRE
assert woodPat instanceof Pattern && piperPat instanceof Pattern

def woodList = woodchuck.split().grep(woodPat)
println ([exactTokenMatches: woodList])
println ([exactTokenMatches: pepper.split().grep(piperPat)])
println ()

println "=== Matcher (=~) operator ==="
def wwMatcher = (woodchuck =~ woodRE)
def ppMatcher = (pepper =~ /[Pp]\w+r/)
def wpMatcher = (woodchuck =~ /[Pp]\w+r/)
assert wwMatcher instanceof Matcher && ppMatcher instanceof Matcher
assert wwMatcher.toString() == woodPat.matcher(woodchuck).toString()
assert ppMatcher.toString() == piperPat.matcher(pepper).toString()
assert wpMatcher.toString() == piperPat.matcher(woodchuck).toString()

println ([ substringMatches: wwMatcher.collect { it }])
println ([ substringMatches: ppMatcher.collect { it }])
println ([ substringMatches: wpMatcher.collect { it }])
println ()

println "=== Exact Match (==~) operator ==="
def containsWoodRE = /.*/ + woodRE + /.*/
def containsPiperRE = /.*/ + piperRE + /.*/
def wwMatches = (woodchuck ==~ containsWoodRE)
assert wwMatches instanceof Boolean
def wwNotMatches = ! (woodchuck ==~ woodRE)
def ppMatches = (pepper ==~ containsPiperRE)
def pwNotMatches = ! (pepper ==~ containsWoodRE)
def wpNotMatches = ! (woodchuck ==~ containsPiperRE)
assert wwMatches && wwNotMatches && ppMatches && pwNotMatches && pwNotMatches

println ("'${woodchuck}' ${wwNotMatches ? 'does not' : 'does'} match '${woodRE}' exactly")
println ("'${woodchuck}' ${wwMatches ? 'does' : 'does not'} match '${containsWoodRE}' exactly")


(defun file-string (path)
  (with-open-file (stream path)
    (let ((data (make-string (file-length stream))))
      (read-sequence data stream)
      data)))


content = File.read("input.txt")
puts content


import std.file: read, readText;

void main() {
    // To read a whole file into a dynamic array of unsigned bytes:
    auto data = cast(ubyte[])read("unixdict.txt");

    // To read a whole file into a validated UTF-8 string:
    string txt = readText("unixdict.txt");
}


import Text.Regex

str = "I am a string"

case matchRegex (mkRegex ".*string$") str of
  Just _  -> putStrLn $ "ends with 'string'"
  Nothing -> return ()


CHARACTER string*100/ "The quick brown fox jumps over the lazy dog" /
REAL, PARAMETER :: Regex=128, Count=256

characters_a_m = INDEX(string, "[a-m]", Regex+Count) ! counts 16

vocals_changed = EDIT(Text=string, Option=Regex, Right="[aeiou]", RePLaceby='**', DO=LEN(string) ) ! changes 11
WRITE(ClipBoard) string ! Th** q****ck br**wn f**x j**mps **v**r th** l**zy d**g


procedure main()

s := "A simple string"
p := "string$"                  # regular expression

s ? write(image(s),if ReFind(p) then " matches " else " doesn't match ",image(p))

s[j := ReFind(p,s):ReMatch(p,s,j)] := "replacement"
write(image(s))
end

link regexp   # link to IPL regexp


program ReadAll;

{$APPTYPE CONSOLE}

uses Classes;

var
  i: Integer;
  lList: TStringList;
begin
  lList := TStringList.Create;
  try
    lList.LoadFromFile('c:\input.txt');
    // Write everything at once
    Writeln(lList.Text);
    // Write one line at a time
    for i := 0 to lList.Count - 1 do
      Writeln(lList[i]);
  finally
    lList.Free;
  end;
end.


defmodule FileReader do
  # Read in the file
  def read(path) do
    case File.read(path) do
      {:ok, body} ->
        IO.inspect body
      {:error,reason} ->
        :file.format_error(reason)
      end
    end

  # Open the file path, then read in the file
  def bit_read(path) do
    case File.open(path) do
      {:ok, file} ->
        # :all can be replaced with :line, or with a positive integer to specify the number of characters to read.
	IO.read(file,:all)
	  |> IO.inspect
      {:error,reason} ->
	:file.format_error(reason)
    end
  end
end


let T be indexed text;
let T be "A simple string";
if T matches the regular expression ".*string$", say "ends with string.";
replace the regular expression "simple" in T with "replacement";


load'regex'               NB.  Load regex library
str =: 'I am a string'   NB.  String used in examples.


String str = "I am a string";
if (str.matches(".*string")) { // note: matches() tests if the entire string is a match
  System.out.println("ends with 'string'");
}


var subject = "Hello world!";

// Two different ways to create the RegExp object
// Both examples use the exact same pattern... matching "hello "
var re_PatternToMatch = /Hello (World)/i; // creates a RegExp literal with case-insensitivity
var re_PatternToMatch2 = new RegExp("Hello (World)", "i");

// Test for a match - return a bool
var isMatch = re_PatternToMatch.test(subject);

// Get the match details
//    Returns an array with the match's details
//    matches[0] == "Hello world"
//    matches[1] == "world"
var matches = re_PatternToMatch2.exec(subject);


(setq my-variable (with-temp-buffer
                    (insert-file-contents "foo.txt")
                    (buffer-string)))


function load_file(sequence filename)
  integer fn,c
  sequence data
    fn = open(filename,"r") -- "r" for text files, "rb" for binary files
    if (fn = -1) then return {} end if -- failed to open the file

    data = {} -- init to empty sequence
    c = getc(fn) -- prime the char buffer
    while (c != -1) do -- while not EOF
      data &= c -- append each character
      c = getc(fn) -- next char
    end while

    close(fn)
    return data
end function


// read entire file into variable using default system encoding or with specified encoding
open System.IO
let data = File.ReadAllText(filename)
let utf8 = File.ReadAllText(filename, System.Text.Encoding.UTF8)


/* Regular expressions, in Jsish */

var re = /s[ai]mple/;
var sentence = 'This is a sample sentence';

var matches = sentence.match(re);
if (matches.length > 0) printf('%s found in "%s" using %q\n', matches[0], sentence, re);

var replaced = sentence.replace(re, "different");
printf("replaced sentence is: %s\n", replaced);


s = "I am a string"
if ismatch(r"string$", s)
    println("'$s' ends with 'string'")
end


// version 1.0.6

fun main(args: Array<String>) {
    val s1 = "I am the original string"
    val r1 = Regex("^.*string$")
    if (s1.matches(r1)) println("`$s1` matches `$r1`")
    val r2 = Regex("original")
    val s3 = "replacement"
    val s2 = s1.replace(r2, s3)
    if (s2 != s1) println("`$s2` replaces `$r2` with `$s3`")
}


USING: io.encodings.ascii io.encodings.binary io.files ;

! to read entire file as binary
"foo.txt" binary file-contents

! to read entire file as lines of text
"foo.txt" ascii file-lines


class ReadString
{
  public static Void main (Str[] args)
  {
    Str contents := File(args[0].toUri).readAllStr
    echo ("contents: $contents")
  }
}


program read_file
    implicit none
    integer :: n
    character(:), allocatable :: s

    open(unit=10, file="read_file.f90", action="read", &
         form="unformatted", access="stream")
    inquire(unit=10, size=n)
    allocate(character(n) :: s)
    read(10) s
    close(10)

    print "(A)", s
end program


' FB 1.05.0 Win64

Open "input.txt" For Input Encoding "ascii" As #1
Dim fileLen As LongInt = Lof(1) '' get file length in bytes
Dim buffer As String = Space(fileLen) '' allocate a string of size 'fileLen' bytes
Get #1, 1, buffer '' read all data from start of file into the buffer
Print buffer  '' print to console
buffer = ""  '' release memory used by setting buffer to empty
Close #1
Sleep


if matching(re/abc/, "somestring") { ... }


local(mytext = 'My name is: Stone, Rosetta
My name is: Hippo, Campus
')

local(regexp = regexp(
		-find = `(?m)^My name is: (.*?), (.*?)$`,
		-input = #mytext,
		-replace = `Hello! I am $2 $1`,
		-ignorecase
))

while(#regexp -> find) => {^
	#regexp -> groupcount > 1 ? (#regexp -> matchString(2) -> trim&) + '
'
^}

#regexp -> reset(-input = #mytext)
#regexp -> findall

#regexp -> reset(-input = #mytext)
'
'
#regexp -> replaceall


test = "My name is Lua."
pattern = ".*name is (%a*).*"

if test:match(pattern) then
    print("Name found.")
end

sub, num_matches = test:gsub(pattern, "Hello, %1!")
print(sub)


Module CheckIt {
      declare global ObjRegEx "VBscript.RegExp"
      Function RegEx.Replace$(from$, what$) {
            Method ObjRegEx, "Replace", from$, what$ as response$
            =response$
      }
      Function RegEx.Test(what$) {
            Method ObjRegEx, "Test", what$ as response
            =response
      }
      Print Type$(ObjRegEx)
      With ObjRegEx, "Global", True, "Pattern" as pattern$
      pattern$="Mona Lisa"
      Print RegEx.Test("The Mona Lisa is in the Louvre.")=true
      Print RegEx.Replace$("The Mona Lisa is in the Louvre.", "La Gioconda")
      Pattern$ = " {2,}"
      Print "Myer Ken,  Vice President,  Sales and Services"
      \\ Removing some spaces
      Print RegEx.Replace$("Myer Ken,  Vice President,  Sales and Services", " ")
      pattern$="(\d{3})-(\d{3})-(\d{4})"

      Method ObjRegEx, "Execute", "555-123-4567, 555-943-6717" as MyMatches
      Print Type$(MyMatches)  ' it is a IMatchCollection2
      With MyMatches, "Count" as count, "Item" as List$()
      For i=0 to Count-1 : Print List$(i) : Next i

      Print RegEx.Replace$("555-123-4567, 555-943-6717", "($1) $2-$3")
      Pattern$ = "(\S+), (\S+)"
      Print RegEx.Replace$("Myer, Ken", "$2 $1")
      Method ObjRegEx, "Execute", "Myer, Ken" as MyMatches
      Rem : DisplayFunctions(MyMatches)
      \\ we can use Enumerator
      With MyMatches, "_NewEnum" as New Matches
      Rem : DisplayFunctions(Matches)
      With Matches, "Value" as New item$
      While Matches {
           Print Item$
      }
      \\ Or just using the list$()
      For i=0 to Count-1 : Print List$(i) : Next i
      declare ObjRegEx Nothing
      End
      Sub DisplayFunctions(x)
            Local cc=param(x),  ec=each(cc)
            while ec {
                  Print eval$(ec)   ' print every function/property of object x
            }
      End Sub
}
Checkit

\\ internal has no pattern. There is a like operator (~) for strings which use pattern matching (using VB6 like). We can use Instr() and RInstr() for strings.

Module Internal {
      what$="Mona Lisa"
      Document a$="The Mona Lisa is in the Louvre."
      Find a$, what$
      Read FindWhere
      If FindWhere<>0 then Read parNo, parlocation
      \\ replace in place
      Insert  FindWhere, Len(what$)  a$="La Gioconda"
      Report a$

      n$="The Mona Lisa is in the Louvre, not the Mona Lisa"
      Report Replace$("Mona Lisa", "La Gioconda", n$, 1, 1)  ' replace from start only one
      dim a$()
      a$()=Piece$("Myer, Ken",", ")
      Print a$(1)+", "+a$(0)="Ken, Myer"
}
Internal


a = read["file:yourfile.txt"]
b = read["file:yourfile.txt", "UTF-8"]


_window = 1
begin enum 1
  _scrollView
  _textView
end enum

void local fn BuildWindow
  CGRect r = {0,0,550,400}
  window _window, @"Read Entire File", r
  scrollview _scrollView, r
  ViewSetAutoresizingMask( _scrollView, NSViewWidthSizable + NSViewHeightSizable )
  textview _textView,, _scrollView
end fn

local fn ReadTextFile
  CFStringRef string
  CFURLRef url = openpanel 1, @"Select text file..."
  if ( url )
    string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
    TextSetString( _textView, string )
  else
    // user cancelled
  end if
end fn

fn BuildWindow
fn ReadTextFile

HandleEvents


Public Sub Form_Open()
Dim sFile As String

sFile = File.Load(User.home &/ "file.txt")

End


InputTextFile("input.txt");
s := ReadAll(f);;  # two semicolons to hide the result, which may be long
CloseStream(f);


[indent=4]
/*
   Read entire file, in Genie

   valac readEntireFile.gs
   ./readEntireFile [filename]
*/

init

    fileName:string
    fileContents:string
    fileName = (args[1] is null) ? "readEntireFile.gs" : args[1]

    try
        FileUtils.get_contents(fileName, out fileContents)
    except exc:Error
        print "Error: %s", exc.message
        return

    stdout.printf("%d bytes read from %s\n", fileContents.length, fileName)


regexp(`GNUs not Unix', `\<[a-z]\w+')
regexp(`GNUs not Unix', `\<[a-z]\(\w+\)', `a \& b \1 c')


#Examples from Maple Help
StringTools:-RegMatch("^ab+bc$", "abbbbc");
StringTools:-RegMatch("^ab+bc$", "abbbbcx");
StringTools:-RegSub("a([bc]*)(c*d)", "abcd", "&-\\1-\\2");
StringTools:-RegSub("(.*)c(anad[ai])(.*)", "Maple is canadian", "\\1C\\2\\3");


StringCases["I am a string with the number 18374 in me",RegularExpression["[0-9]+"]]
StringReplace["I am a string",RegularExpression["I\\sam"] -> "I'm"]


samples = #("Some string 123","Example text 123","string",\
	    "ThisString Will Not Match","A123,333,string","123451")
samples2 = #("I am a string","Me too.")

regex = dotnetobject "System.Text.RegularExpressions.Regex" ".*\bstring*"
regex2 = dotnetobject "System.Text.RegularExpressions.Regex" "\ba\b"

clearlistener()

format "Pattern is : %\n" (regex.toString())

for i in samples do
(
	if regex.ismatch(i) then
	(
		format "The string \"%\" matches the pattern\n" i
	)
	else
	(
		format "The string \"%\" doesn't match the pattern\n" i
	)
)

-- replacement

format "Pattern is : %\n" (regex2.toString())

for i in samples2 do
(
	if regex2.ismatch(i) then
	(
		local replaced = regex2.replace i "another"
		format "The string \"%\" matched the pattern, so it was replaced: \"%\"\n" i replaced
	)
	else
	(
		format "The string \"%\" does not match the pattern\n" i
	)
)


import "io/ioutil"

data, err := ioutil.ReadFile(filename)
sv := string(data)


def fileContent = new File("c:\\file.txt").text


do text <- readFile filepath
   -- do stuff with text


alias regular_expressions {
  var %string = This is a string
  var %re = string$
  if ($regex(%string,%re) > 0) {
    echo -a Ends with string.
  }
  %re = \ba\b
  if ($regsub(%string,%re,another,%string) > 0) {
    echo -a Result 1: %string
  }
  %re = \b(another)\b
  echo -a Result 2: $regsubex(%string,%re,yet \1)
}


REGEXP
 NEW HI,W,PATTERN,BOOLEAN
 SET HI="Hello, world!",W="world"
 SET PATTERN=".E1"""_W_""".E"
 SET [email protected]
 WRITE "Source string - '"_HI_"'",!
 WRITE "Partial string - '"_W_"'",!
 WRITE "Pattern string created is - '"_PATTERN_"'",!
 WRITE "Match? ",$SELECT(BOOLEAN:"YES",'BOOLEAN:"No"),!
 ;
 SET BOOLEAN=$FIND(HI,W)
 IF BOOLEAN>0 WRITE $PIECE(HI,W,1)_"string"_$PIECE(HI,W,2)
 QUIT


/* NetRexx */
options replace format comments java crossref symbols nobinary

import java.util.regex.

st1 = 'Fee, fie, foe, fum, I smell the blood of an Englishman'
rx1 = 'f.e.*?'
sbx = 'foo'

rx1ef = '(?i)'rx1 -- use embedded flag expression == Pattern.CASE_INSENSITIVE

-- using String's matches & replaceAll
mcm = (String st1).matches(rx1ef)
say 'String "'st1'"' 'matches pattern "'rx1ef'":' Boolean(mcm)
say
say 'Replace all occurrences of regex pattern "'rx1ef'" with "'sbx'"'
stx = Rexx
stx = (String st1).replaceAll(rx1ef, sbx)
say 'Input string:  "'st1'"'
say 'Result string: "'stx'"'
say

-- using java.util.regex classes
pt1 = Pattern.compile(rx1, Pattern.CASE_INSENSITIVE)
mc1 = pt1.matcher(st1)
mcm = mc1.matches()
say 'String "'st1'"' 'matches pattern "'pt1.toString()'":' Boolean(mcm)
mc1 = pt1.matcher(st1)
say
say 'Replace all occurrences of regex pattern "'rx1'" with "'sbx'"'
sx1 = Rexx
sx1 = mc1.replaceAll(sbx)
say 'Input string:  "'st1'"'
say 'Result string: "'sx1'"'
say

return


Home is a room.

The File of Testing is called "test".

When play begins:
	say "[text of the File of Testing]";
	end the story.


   require 'files'         NB. not needed for J7 & later
   var=: freads 'foo.txt'


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
    public static void main(String[] args) throws IOException{
        String fileContents = readEntireFile("./foo.txt");
    }

    private static String readEntireFile(String filename) throws IOException {
        FileReader in = new FileReader(filename);
        StringBuilder contents = new StringBuilder();
        char[] buffer = new char[4096];
        int read = 0;
        do {
            contents.append(buffer, 0, read);
            read = in.read(buffer);
        } while (read >= 0);
        in.close();
        return contents.toString();
    }
}


var fso=new ActiveXObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile("c:\\myfile.txt",1);
var s=f.ReadAll();
f.Close();
try{alert(s)}catch(e){WScript.Echo(s)}


(regex "[bB]+" "AbBBbABbBAAAA") -> ("bBBb" 1 4)


import re

var s = "This is a string"

if s.find(re"string$") > -1:
  echo "Ends with string."

s = s.replace(re"\ a\ ", " another ")
echo s


use RegEx;

bundle Default {
  class RegExTest {
    function : Main(args : String[]) ~ Nil {
      string := "I am a string";
      # exact match
      regex := RegEx->New(".*string");
      if(regex->MatchExact(".*string")) {
        "ends with 'string'"->PrintLine();
      };
      # replace all
      regex := RegEx->New(" a ");
      regex->ReplaceAll(string, " another ")->PrintLine();
    }
  }
}


read("/devel/myfile.txt", String) # read file into a string


import java.io.File

fun main(args: Array<String>) {
    println(File("unixdict.txt").readText(charset = Charsets.UTF_8))
}


NSString *str = @"I am a string";
NSString *regex = @".*string$";

// Note: the MATCHES operator matches the entire string, necessitating the ".*"
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

if ([pred evaluateWithObject:str]) {
    NSLog(@"ends with 'string'");
}


#load "str.cma";;
let str = "I am a string";;
try
  ignore(Str.search_forward (Str.regexp ".*string$") str 0);
  print_endline "ends with 'string'"
with Not_found -> ()
;;


; matching:
(define regex (string->regex "m/aa(bb|cc)dd/"))
(print (regex "aabbddx")) ; => true
(print (regex "aaccddx")) ; => true
(print (regex "aabcddx")) ; => false

; substitute part of a string:
(define regex (string->regex "s/aa(bb|cc)dd/HAHAHA/"))
(print (regex "aabbddx")) ; => HAHAHAx
(print (regex "aaccddx")) ; => HAHAHAx
(print (regex "aabcddx")) ; => false


local(f) = file('foo.txt')
#f->readString


(set `#(ok ,data) (file:read_file "myfile.txt"))


filedialog "Open a Text File","*.txt",file$
if file$<>"" then
    open file$ for input as #1
    entire$ = input$(#1, lof(#1))
    close #1
    print entire$
end if


F recamanSucc(seen, n, r)
   ‘The successor for a given Recaman term,
    given the set of Recaman terms seen so far.’
   V back = r - n
   R I 0 > back | (back C seen) {n + r} E back

F recamanUntil(p)
   ‘All terms of the Recaman series before the
    first term for which the predicate p holds.’
   V n = 1
   V r = 0
   V rs = [r]
   V seen = Set(rs)
   V blnNew = 1B
   L !p(seen, n, r, blnNew)
      r = recamanSucc(seen, n, r)
      blnNew = r !C seen
      seen.add(r)
      rs.append(r)
      n = 1 + n
   R rs

F enumFromTo(m)
   ‘Integer enumeration from m to n.’
   R n -> @m .< 1 + n

print("First 15 Recaman:\n "recamanUntil((seen, n, r, _) -> n == 15))
print("First duplicated Recaman:\n "recamanUntil((seen, n, r, blnNew) -> !blnNew).last)
V setK = Set(enumFromTo(0)(1000))
print("Number of Recaman terms needed to generate all integers from [0..1000]:\n "(recamanUntil((seen, n, r, blnNew) -> (blnNew & r < 1001 & :setK.is_subset(seen))).len - 1))


/* Rexx */
/* Using the RxRegExp Regular Expression built-in utility class */

st1 = 'Fee, fie, foe, fum, I smell the blood of an Englishman'
rx1 = '[Ff]?e' -- unlike most regex engines, RxRegExp uses '?' instead of '.' to match any single character
sbx = 'foo'

myRE = .RegularExpression~new()
myRE~parse(rx1, MINIMAL)

mcm = myRE~pos(st1)
say 'String "'st1'"' 'matches pattern "'rx1'":' bool2string(mcm > 0)
say

-- The RxRegExp package doesn't provide a replace capability so you must roll your own
st0 = st1
loop label GREP forever
  mcp = myRE~pos(st1)
  if mcp > 0 then do
    mpp = myRE~position
    fnd = st1~substr(mcp, mpp - mcp + 1)
    stx = st1~changestr(fnd, sbx, 1)
    end
  else leave GREP
  st1 = stx
  end GREP
say 'Input string:  "'st0'"'
say 'Result string: "'stx'"'
return
exit

bool2string:
procedure
do
  parse arg bv .
  if bv then bx = 'true'
        else bx = 'false'
  return bx
end
exit

::requires "rxregexp.cls"


// Match and Replace part of a string using a Regular Expression
//
// Nigel Galloway - April 15th., 2012
//
namespace re;

interface

type
  re = class
  public
    class method Main;
  end;

implementation

class method re.Main;
const
  myString = 'I think that I am Nigel';
var
  r: System.Text.RegularExpressions.Regex;
  myResult : String;
begin
  r := new System.Text.RegularExpressions.Regex('(I am)|(you are)');
  Console.WriteLine("{0} contains {1}", myString, r.Match(myString));
  myResult := r.Replace(myString, "you are");
  Console.WriteLine("{0} contains {1}", myResult, r.Match(myResult));
end;

end.


----------------------------------------
-- Reads whole file, returns string
-- @param {string} tFile
-- @return {string|false}
----------------------------------------
on readFile (tFile)
  fp = xtra("fileIO").new()
  fp.openFile(tFile, 1)
  if fp.status() then return false
  res = fp.readFile()
  fp.closeFile()
  return res
end


put URL "file:///usr/share/dict/words" into tVar
put the number of lines of tVar


--If the file opens with no problems, io.open will return a
--handle to the file with methods attached.
--If the file does not exist, io.open will return nil and
--an error message.
--assert will return the handle to the file if present, or
--it will throw an error with the message returned second
--by io.open.
local file = assert(io.open(filename))
--Without wrapping io.open in an assert, local file would be nil,
--which would cause an 'attempt to index a nil value' error when
--calling file:read.

--file:read takes the number of bytes to read, or a string for
--special cases, such as "*a" to read the entire file.
local contents = file:read'*a'

--If the file handle was local to the expression
--(ie. "assert(io.open(filename)):read'a'"),
--the file would remain open until its handle was
--garbage collected.
file:close()


Module checkit {
      \\ prepare a file
      \\ Save.Doc and Append.Doc  to file, Load.Doc and Merge.Doc from file
      document a$
      a$={First Line
            Second line
            Third Line
            Ελληνικά Greek Letters
            }
      Save.Doc a$, "checkthis.txt", 2  ' 2 for UTF-8

      Buffer1=Buffer("checkthis.txt")
      Print Len(Buffer1)=Filelen("checkthis.txt")
      b$=String$(Eval$(Buffer1, 0) as UTF8Dec)
      Report b$
      openfile$=FILE$("text file","txt")
      Merge.doc a$, openfile$
      Edit.Doc a$
}
checkit


begin
    % calculate Recaman's sequence values                                              %

    % a hash table element - holds n, A(n) and a link to the next element with the     %
    %                        same hash value                                           %
    record AValue ( integer eN, eAn ; reference(AValue) eNext );

    % hash modulus                                                                     %
    integer HMOD;
    HMOD := 100000;

    begin
        reference(AValue) array hashTable ( 0 :: HMOD - 1 );
        integer array A ( 0 :: 14 );
        integer le1000Count, firstN, duplicateN, duplicateValue, n, An, An1, prevN, maxS;

        % adds an element to the hash table, returns true if an element with value An  %
        % was already present, false otherwise                                         %
        % if the value was already present, its eN value is returned in prevN          %
        logical procedure addAValue( integer value n, An ; integer result prevN ) ;
            begin
                integer hash;
                logical duplicate;
                reference(AValue) element;
                hash      := An rem HMOD;
                element   := hashTable( hash );
                duplicate := false;
                while element not = null and eAn(element) not = An do element := eNext(element);
                duplicate := element not = null;
                if not duplicate then hashTable( hash ) := AValue( n, An, hashTable( hash ) )
                                 else prevN := eN(element);
                duplicate
            end addAValue ;

        % initialise the hash table                                                    %
        for h := 0 until HMOD - 1 do hashTable( h ) := null;

        % calculate the values of the sequence until we have found values that         %
        % include all numbers in 1..1000                                               %
        % also store the first 15 values                                               %

        A( 0 ) := An1 := n := 0;
        le1000Count := 0;
        maxS := firstN := duplicateN := duplicateValue := -1;
        while le1000Count < 1000 do begin
            logical le0, duplicate;
            n  := n + 1;
            An := An1 - n;
            le0 := ( An <= 0 );
            if le0 then An := An1 + n;
            prevN := -1;
            duplicate := addAValue( n, An, prevN );
            if duplicate and not le0 then begin
                An := An1 + n;
                duplicate := addAValue( n, An, prevN )
            end if_duplicate_and_not_le0 ;
            if duplicate then begin
                % the value was already present %
                if firstN < 0 then begin   % have the first duplicate                  %
                    firstN         := n;
                    duplicateN     := prevN;
                    duplicateValue := An;
                end if_firstN_lt_0
                end
            else if An <= 1000 then le1000Count := le1000Count + 1;;
            if n < 15 then A( n ) := An;
            if An > maxS then maxS := An;
            An1 := An
        end while_le1000Count_lt_1000 ;

        % show the first 15 values of the sequence                                     %
        write( "A( 0 .. 14 ): " );
        for n := 0 until 14 do writeon( i_w := 1, A( n ) );
        % positions of the first duplicate                                             %
        write( i_w := 1
               , s_w := 0
               , "First duplicates: "
               , duplicateN
               , " "
               , firstN
               , " ("
               , duplicateValue
               , ")"
               );
        % number of elements required to include the first 1000 integers               %
        write( i_w := 1, "first element to include all 1..1000: ", n );
        write( i_w := 1, "max sequence value encountered: ", maxS )
    end

end.


recaman←{⎕IO←0
    genNext←{
        R←⍵[N-1]-N←≢⍵
        (R<0)∨(R∊⍵):⍵,⍵[N-1]+N
        ⍵,⍵[N-1]-N
    }
    ⎕←'First 15: '
    ⎕←reca←(genNext⍣14),0
    ⎕←'First repetition: '
    ⎕←⊃⌽reca←genNext⍣{⍺≢∪⍺}⊢reca
    ⎕←'Length of sequence containing [0..1000]:'
    ⎕←≢reca←genNext⍣{(⍳1001)∧.∊⊂⍺}⊢reca
}


use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

on run

  -- FIRST FIFTEEN RECAMANs ------------------------------------------------------

  script term15
    on |λ|(i)
      15 = (i as integer)
    end |λ|
  end script
  set strFirst15 to unwords(snd(recamanUpto(true, term15)))

  set strFirstMsg to "First 15 Recamans:" & linefeed
  display notification strFirstMsg & strFirst15
  delay 2

  -- FIRST DUPLICATE RECAMAN ----------------------------------------------------

  script firstDuplicate
    on |λ|(_, seen, rs)
      setSize(seen) as integer is not (length of (rs as list))
    end |λ|
  end script
  set strDuplicate to (item -1 of snd(recamanUpto(true, firstDuplicate))) as integer as string

  set strDupMsg to "First duplicated Recaman:" & linefeed
  display notification strDupMsg & strDuplicate
  delay 2

  -- NUMBER OF RECAMAN TERMS NEEDED TO GET ALL OF [0..1000]
  -- (takes about a minute, depending on system)

  set setK to setFromList(enumFromTo(0, 1000))
  script supersetK
    on |λ|(i, setR)
      setK's isSubsetOfSet:(setR)
    end |λ|
  end script

  display notification "Superset size result will take c. 1 min to find ..."
  set dteStart to current date

  set strSetSize to (fst(recamanUpto(false, supersetK)) - 1) as string

  set dteEnd to current date

  set strSetSizeMsg to "Number of Recaman terms needed to generate" & ¬
    linefeed & "all integers from [0..1000]:" & linefeed
  set strElapsed to "(Last result took c. " & (dteEnd - dteStart) & " seconds to find)"
  display notification strSetSizeMsg & linefeed & strSetSize

  -- CLEARED REFERENCE TO NSMUTABLESET -------------------------------------
  set setK to missing value

  -- REPORT ----------------------------------------------------------------
  unlines({strFirstMsg & strFirst15, "", ¬
    strDupMsg & strDuplicate, "", ¬
    strSetSizeMsg & strSetSize, "", ¬
    strElapsed})
end run

-- nextR :: Set Int -> Int -> Int
on nextR(seen, i, n)
  set bk to n - i
  if 0 > bk or setMember(bk, seen) then
    n + i
  else
    bk
  end if
end nextR

-- recamanUpto :: Bool -> (Int -> Set Int > [Int] -> Bool) -> (Int, [Int])
on recamanUpto(bln, p)
  script recaman
    property mp : mReturn(p)'s |λ|
    on |λ|()
      set i to 1
      set r to 0
      set rs to {r}
      set seen to setFromList(rs)
      repeat while not mp(i, seen, rs)
        set r to nextR(seen, i, r)
        setInsert(r, seen)
        if bln then set end of rs to r
        set i to i + 1
      end repeat
      set seen to missing value -- clear pointer to NSMutableSet
      {i, rs}
    end |λ|
  end script
  recaman's |λ|()
end recamanUpto

-- GENERIC FUNCTIONS -------------------------------------------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
  if m ≤ n then
    set lst to {}
    repeat with i from m to n
      set end of lst to i
    end repeat
    return lst
  else
    return {}
  end if
end enumFromTo

-- fst :: (a, b) -> a
on fst(tpl)
  if class of tpl is record then
    |1| of tpl
  else
    item 1 of tpl
  end if
end fst

-- intercalateS :: String -> [String] -> String
on intercalateS(sep, xs)
  set {dlm, my text item delimiters} to {my text item delimiters, sep}
  set s to xs as text
  set my text item delimiters to dlm
  return s
end intercalateS

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
  if class of f is script then
    f
  else
    script
      property |λ| : f
    end script
  end if
end mReturn

-- NB All names of NSMutableSets should be set to *missing value*
-- before the script exits.
-- ( scpt files containing residual ObjC pointer values can not be saved)
-- setFromList :: Ord a => [a] -> Set a
on setFromList(xs)
  set ca to current application
  ca's NSMutableSet's ¬
    setWithArray:(ca's NSArray's arrayWithArray:(xs))
end setFromList

-- setMember :: Ord a => a -> Set a -> Bool
on setMember(x, objcSet)
  missing value is not (objcSet's member:(x))
end setMember

-- setInsert :: Ord a => a -> Set a -> Set a
on setInsert(x, objcSet)
  objcSet's addObject:(x)
  objcSet
end setInsert

-- setSize :: Set a -> Int
on setSize(objcSet)
  objcSet's |count|() as integer
end setSize

-- snd :: (a, b) -> b
on snd(tpl)
  if class of tpl is record then
    |2| of tpl
  else
    item 2 of tpl
  end if
end snd

-- unlines :: [String] -> String
on unlines(xs)
  set {dlm, my text item delimiters} to ¬
    {my text item delimiters, linefeed}
  set str to xs as text
  set my text item delimiters to dlm
  str
end unlines

-- unwords :: [String] -> String
on unwords(xs)
  intercalateS(space, xs)
end unwords


declare
  [Regex] = {Module.link ['x-oz://contrib/regex']}
  String = "This is a string"
in
  if {Regex.search "string$" String} \= false then
     {System.showInfo "Ends with string."}
  end
  {System.showInfo {Regex.replace String " a " fun {$ _ _} " another " end}}


// Match and Replace part of a string using a Regular Expression
//
// Nigel Galloway - April 11th., 2012
//
program RegularExpr;

uses
  RegExpr;

const
  myString = 'I think that I am Nigel';
  myMatch = '(I am)|(you are)';
var
  r : TRegExpr;
  myResult : String;

begin
  r := TRegExpr.Create;
  r.Expression := myMatch;
  write(myString);
  if r.Exec(myString) then writeln(' contains ' + r.Match[0]);
  myResult := r.Replace(myString, 'you are', False);
  write(myResult);
  if r.Exec(myResult) then writeln(' contains ' + r.Match[0]);
end.


$string = "I am a string";
if ($string =~ /string$/) {
   print "Ends with 'string'\n";
}

if ($string !~ /^You/) {
   print "Does not start with 'You'\n";
}


s1 := readbytes( "file1.txt", infinity, TEXT ):


  fid = fopen('filename','r');
  [str,count] = fread(fid, [1,inf], 'uint8=>char');  % s will be a character array, count has the number of bytes
  fclose(fid);


:- module read_entire_file.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module string.

main(!IO) :-
   io.open_input("file.txt", OpenResult, !IO),
   (
      OpenResult = ok(File),
      io.read_file_as_string(File, ReadResult, !IO),
      (
           ReadResult = ok(FileContents),
           io.write_string(FileContents, !IO)
      ;
           ReadResult = error(_, IO_Error),
           io.stderr_stream(Stderr, !IO),
           io.write_string(Stderr, io.error_message(IO_Error) ++ "\n", !IO)
      )
   ;
      OpenResult = error(IO_Error),
      io.stderr_stream(Stderr, !IO),
      io.write_string(Stderr, io.error_message(IO_Error) ++ "\n", !IO)
   ).


recamanSucc: function [seen, n, r].memoize[
    back: r - n
    (or? 0 > back contains? seen back)? -> n + r
                                        -> back
]

recamanUntil: function [p][
    n: new 1
    r: 0
    rs: new @[r]
    seen: rs
    blnNew: true
    while [not? do p][
        r: recamanSucc seen n r
        blnNew: not? in? r seen
        seen: unique seen ++ r
        'rs ++ r
        inc 'n
    ]
    return rs
]

print "First 15 Recaman numbers:"
print recamanUntil [n = 15]

print ""
print "First duplicate Recaman number:"
print last recamanUntil [not? blnNew]


# syntax: GAWK -f RECAMANS_SEQUENCE.AWK
# converted from Microsoft Small Basic
BEGIN {
    found_dup = 0
    n = -1
    do {
      n++
      ap = a[n-1] + n
      if (a[n-1] <= n) {
        a[n] = ap
        b[ap] = 1
      }
      else {
        am = a[n-1] - n
        if (b[am] == 1) {
          a[n] = ap
          b[ap] = 1
        }
        else {
          a[n] = am
          b[am] = 1
        }
      }
      if (n <= 14) {
        terms = sprintf("%s%s ",terms,a[n])
        if (n == 14) {
          printf("first %d terms: %s\n",n+1,terms)
        }
      }
      if (!found_dup) {
        if (dup[a[n]] == 1) {
          printf("first duplicated term: a[%d]=%d\n",n,a[n])
          found_dup = 1
        }
        dup[a[n]] = 1
      }
      if (a[n] <= 1000) {
        arr[a[n]] = ""
      }
    } while (n <= 15 || !found_dup || length(arr) < 1001)
    printf("terms needed to generate integers 0 - 1000: %d\n",n)
    exit(0)
}


with javascript_semantics
include builtins\regex.e
requires("1.0.2") -- (needs some recent bugfixes to regex.e for p2js)
string s = "I am a string"
printf(1,"\"%s\" %s with string\n",{s,iff(length(regex(`string$`,s))?"ends":"does not end")})
printf(1,"\"%s\" %s with You\n",{s,iff(length(regex(`^You`,s))?"starts":"does not start")})
?gsub(`[A-Z]`,"abCDefG","*")
?gsub(`[A-Z]`,"abCDefGH","(&)")
?gsub(`[A-Z]+`,"abCDefGH","(&)")
?gsub(`string`,s,"replacement")
s = gsub(`\ba\b`,s,"another") ?s
?gsub(`string`,s,"replacement")


$string = 'I am a string';
# Test
if (preg_match('/string$/', $string))
{
    echo "Ends with 'string'\n";
}
# Replace
$string = preg_replace('/\ba\b/', 'another', $string);
echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";


import Nanoquery.IO
contents = new(File, "example.txt").readAll()


/**
 Read entire file
 Tectonics:
   nekoc read-entire-file.neko
   neko read-entire-file
*/

var file_contents = $loader.loadprim("[email protected]_contents", 1);

try {
  var entire_file = file_contents("read-entire-file.neko");
  $print("Read: ", $ssize(entire_file), " bytes\n");
} catch e {
  $print("Exception: ", e, "\n");
}


/* NetRexx */
options replace format comments java crossref symbols nobinary

parse arg inFileName .

if inFileName = '' | inFileName = '.' then inFileName = './data/dwarfs.json'
fileContents = slurp(inFileName)
say fileContents

return

-- Slurp a file and return contents as a Rexx string
method slurp(inFileName) public static returns Rexx

  slurped = Rexx null
  slurpStr = StringBuilder()
  ioBuffer = byte[1024]
  inBytes = int 0

  do
    inFile = File(inFileName)
    inFileIS = BufferedInputStream(FileInputStream(inFile))

    loop label ioLoop until inBytes = -1
      slurpStr.append(String(ioBuffer, 0, inBytes))
      inBytes = inFileIS.read(ioBuffer)
      end ioLoop

  catch exFNF = FileNotFoundException
    exFNF.printStackTrace
  catch exIO = IOException
    exIO.printStackTrace
  finally
    do
      inFileIS.close()
    catch ex = IOException
      ex.printStackTrace
    end
  end

  slurped = Rexx(slurpStr.toString)

  return slurped


10 DEFINT A-Z: DIM A(100)
20 PRINT "First 15 terms:"
30 FOR N=0 TO 14: GOSUB 100: PRINT A(N);: NEXT
35 PRINT
40 PRINT "First repeated term:"
50 GOSUB 100
55 FOR M=0 TO N-1: IF A(M)=A(N) THEN 70 ELSE NEXT
60 N=N+1: GOTO 50
70 PRINT "A(";N;") =";A(N)
80 END
100 IF N=0 THEN A(0)=0: RETURN
110 X = A(N-1)-N: IF X<0 THEN 160
120 FOR M=0 TO N-1
130 IF A(M)=X THEN 160
140 NEXT
150 A(N)=X: RETURN
160 A(N)=A(N-1)+N: RETURN


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
        resultis subterm
    $)

let start() be
$(  let a = vec 50 and n = 15 and rep = ?

    writef("First %N members:*N", n)
    for i = 0 to n-1
    $(  generate(a, i)
        writef("%N ", a!i)
    $)

    writef("*NFirst repeated term:*N")
    rep := valof
    $(  generate(a, n)
        for i = 0 to n-1
            if a!i = a!n resultis n
        n := n + 1
    $) repeat

    writef("a!%N = %N*N", rep, a!rep)
$)


#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_equal);
    a = malloc(400000 * sizeof(int));
    a[0] = 0;
    g_hash_table_add(used, GINT_TO_POINTER(0));
    g_hash_table_add(used1000, GINT_TO_POINTER(0));

    for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {
        next = a[n - 1] - n;
        if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {
            next += 2 * n;
        }
        alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));
        a[n] = next;

        if (!alreadyUsed) {
            g_hash_table_add(used, GINT_TO_POINTER(next));
            if (next >= 0 && next <= 1000) {
                g_hash_table_add(used1000, GINT_TO_POINTER(next));
            }
        }

        if (n == 14) {
            printf("The first 15 terms of the Recaman's sequence are: ");
            printf("[");
            for (i = 0; i < 15; ++i) printf("%d ", a[i]);
            printf("\b]\n");
        }

        if (!foundDup && alreadyUsed) {
            printf("The first duplicated term is a[%d] = %d\n", n, next);
            foundDup = TRUE;
        }
        k = g_hash_table_size(used1000);

        if (k == 1001) {
            printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
        }
    }
    g_hash_table_destroy(used);
    g_hash_table_destroy(used1000);
    free(a);
    return 0;
}


math:e   // e
math:pi  // pi
sqrt(x)  // square root
log(x)   // natural logarithm
log10(x) // base 10 logarithm
exp(x)   // e raised to the power of x
abs(x)   // absolute value
floor(x) // floor
ceil(x)  // ceiling
x ^ y    // exponentiation


(let (Pat "a[0-9]z"  String "a7z")
   (use Preg
      (native "@" "regcomp" 'I '(Preg (64 B . 64)) Pat 1)  # Compile regex
      (when (=0 (native "@" "regexec" 'I (cons NIL (64) Preg) String 0 0 0))
         (prinl "String \"" String "\" matches regex \"" Pat "\"") ) ) )


"I am a string" -match '\bstr'       # true
"I am a string" -replace 'a\b','no'  # I am no string


String$        = "<tag>some text consisting of Roman letters spaces and numbers like 12</tag>"
regex$         = "<([a-z]*)>[a-z,A-Z,0-9, ]*</\1>"
regex_replace$ = "letters[a-z,A-Z,0-9, ]*numbers[a-z,A-Z,0-9, ]*"
If CreateRegularExpression(1, regex$) And CreateRegularExpression(2, regex_replace$)
  If MatchRegularExpression(1, String$)
    Debug "Tags correct, and only alphanummeric or space characters between them"
  EndIf
  Debug ReplaceRegularExpression(2, String$, "char stuff")
EndIf


import re

string = "This is a string"

if re.search('string$', string):
    print("Ends with string.")

string = re.sub(" a ", " another ", string)
print(string)


    /*** 0. PREPARATION    */
    // We need a text file to read; let's redirect a C string to a new file
    // using the shell by way of the stdlib system() function.
    system ("echo \"Hello, World!\" > ~/HelloRosetta");

    /*** 1. THE TASK      */
    // Instantiate an NSString which describes the filesystem location of
    // the file we will be reading.
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"HelloRosetta"];

    // The selector we're going to use to complete this task,
    // stringWithContentsOfFile:encoding:error, has an optional `error'
    // parameter which can be used to return information about any
    // errors it might run into. It's optional, but we'll create an NSError
    // anyways to demonstrate best practice.
    NSError *anError;

    // And finally, the task: read and store the contents of a file as an
    // NSString.
    NSString *aString = [NSString stringWithContentsOfFile:filePath
                                                  encoding:NSUTF8StringEncoding
                                                     error:&anError];

    // If the file read was unsuccessful, display the error description.
    // Otherwise, display the NSString.
    if (!aString) {
        NSLog(@"%@", [anError localizedDescription]);
    } else {
        NSLog(@"%@", aString);
    }


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 };
            bool foundDup = false;
            int n = 1;
            while (n <= 15 || !foundDup || used1000.Count < 1001) {
                int next = a[n - 1] - n;
                if (next < 1 || used.Contains(next)) {
                    next += 2 * n;
                }
                bool alreadyUsed = used.Contains(next);
                a.Add(next);
                if (!alreadyUsed) {
                    used.Add(next);
                    if (0 <= next && next <= 1000) {
                        used1000.Add(next);
                    }
                }
                if (n == 14) {
                    Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
                }
                if (!foundDup && alreadyUsed) {
                    Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
                    foundDup = true;
                }
                if (used1000.Count == 1001) {
                    Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
                }
                n++;
            }
        }
    }
}


#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) {
        os << ", " << *i;
        i = std::next(i);
    }
    return os << ']';
}

int main() {
    using namespace std;

    vector<int> a{ 0 };
    set<int> used{ 0 };
    set<int> used1000{ 0 };
    bool foundDup = false;
    int n = 1;
    while (n <= 15 || !foundDup || used1000.size() < 1001) {
        int next = a[n - 1] - n;
        if (next < 1 || used.find(next) != used.end()) {
            next += 2 * n;
        }
        bool alreadyUsed = used.find(next) != used.end();
        a.push_back(next);
        if (!alreadyUsed) {
            used.insert(next);
            if (0 <= next && next <= 1000) {
                used1000.insert(next);
            }
        }
        if (n == 14) {
            cout << "The first 15 terms of the Recaman sequence are: " << a << '\n';
        }
        if (!foundDup && alreadyUsed) {
            cout << "The first duplicated term is a[" << n << "] = " << next << '\n';
            foundDup = true;
        }
        if (used1000.size() == 1001) {
            cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n";
        }
        n++;
    }

    return 0;
}


GetAbs: ;assumes value we want to abs() is loaded into accumulator
eor #$ff
clc
adc #1
rts


(floor 15 2) ;; This is the floor of 15/2
(ceiling 15 2)
(expt 15 2) ;; 15 squared


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)
  Print(" by Power(") PrintR(a)
  PrintE(",0.5)")

  ValR("2.5",a)
  Ln(a,b)
  Print("Ln(") PrintR(a)
  Print(")=") PrintRE(b)

  ValR("14.2",a)
  Log10(a,b)
  Print("Log10(") PrintR(a)
  Print(")=") PrintRE(b)

  ValR("-3.7",a)
  Exp(a,b)
  Print("Exp(") PrintR(a)
  Print(")=") PrintRE(b)

  ValR("2.6",a)
  Exp10(a,b)
  Print("Exp10(") PrintR(a)
  Print(")=") PrintRE(b)

  ValR("25.3",a)
  ValR("1.3",b)
  Power(a,b,c)
  Print("Power(") PrintR(a)
  Print(",") PrintR(b)
  Print(")=") PrintRE(c)

  ValR("-32.5",a)
  RealAbs(a,b)
  Print("Abs(") PrintR(a)
  Print(")=") PrintR(b)
  PrintE(" by bit manipulation")

  ValR("23.15",a)
  i=Floor(a)
  Print("Floor(") PrintR(a)
  PrintF(")=%I by own function%E",i)

  ValR("-23.15",a)
  i=Floor(a)
  Print("Floor(") PrintR(a)
  PrintF(")=%I by own function%E",i)

  ValR("23.15",a)
  i=Ceiling(a)
  Print("Ceiling(") PrintR(a)
  PrintF(")=%I by own function%E",i)

  ValR("-23.15",a)
  i=Ceiling(a)
  Print("Ceiling(") PrintR(a)
  PrintF(")=%I by own function%E",i)

  PutE()
  PrintE("There is no support in Action! for pi.")
RETURN


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


pattern <- "string"
text1 <- "this is a matching string"
text2 <- "this does not match"


#lang racket

(define s "I am a string")

(when (regexp-match? #rx"string$" s)
  (displayln "Ends with 'string'."))

(unless (regexp-match? #rx"^You" s)
  (displayln "Does not start with 'You'."))

(displayln (regexp-replace " a " s " another "))


if 'a long string' ~~ /string$/ {
   say "It ends with 'string'";
}

# substitution has a few nifty features

$_ = 'The quick Brown fox';
s:g:samecase/\w+/xxx/;
.say;
# output:
# Xxx xxx Xxx xxx


let load_file f =
  let ic = open_in f in
  let n = in_channel_length ic in
  let s = Bytes.create n in
  really_input ic s 0 n;
  close_in ic;
  (s)


(define content (bytes->string
   (vec-iter
      (file->vector "file.txt"))))

(print content)


file = 'c:\test.txt'
myStream = .stream~new(file)
myString = myStream~charIn(,myStream~chars)


declare
  FileHandle = {New Open.file init(name:"test.txt")}
  FileContents = {FileHandle read(size:all list:$)}
in
  {FileHandle close}
  {System.printInfo FileContents}