DEFINE PTR="CARD"

PROC OutputText(CHAR ARRAY s)
  PrintE(s)
RETURN

PROC Procedure=*(CHAR ARRAY s)
  DEFINE JSR="$20"
  DEFINE RTS="$60"
  [JSR $00 $00 ;JSR to address set by SetProcedure
   RTS]

PROC SetProcedure(PTR p)
  PTR addr

  addr=Procedure+1 ;location of address of JSR
  PokeC(addr,p)
RETURN

PROC Repeat(PTR procFun CHAR ARRAY s BYTE n)
  BYTE i

  SetProcedure(procFun)
  FOR i=1 TO n
  DO
    Procedure(s)
  OD
RETURN

PROC Main()
  Repeat(OutputText,"Action!",5)
RETURN


with Ada.Text_IO;

procedure Repeat_Example is

   procedure Repeat(P: access Procedure; Reps: Natural) is
   begin
      for I in 1 .. Reps loop
	 P.all; -- P points to a procedure, and P.all actually calls that procedure
      end loop;
   end Repeat;

   procedure Hello is
   begin
      Ada.Text_IO.Put("Hello! ");
   end Hello;

begin
   Repeat(Hello'Access, 3); -- Hello'Access points to the procedure Hello
end Repeat_Example;


# operator that executes a procedure the specified number of times            #
OP REPEAT = ( INT count, PROC VOID routine )VOID:
    TO count DO routine OD;

# make REPEAT a low priority operater                                         #
PRIO REPEAT = 1;

# can also create variant that passes the iteration count as a parameter      #
OP REPEAT = ( INT count, PROC( INT )VOID routine )VOID:
    FOR iteration TO count DO routine( iteration ) OD;

main: (

    # PROC to test the REPEAT operator with                                   #
    PROC say something = VOID: print( ( "something", newline ) );

    3 REPEAT say something;

    # PROC to test the variant                                                #
    PROC show squares = ( INT n )VOID: print( ( n, n * n, newline ) );

    3 REPEAT show squares

)


(defun repeat-string (n string)
  (with-output-to-string (stream)
    (loop repeat n do (write-string string stream))))


import std.stdio, std.array;

void main() {
    writeln("ha".replicate(5));
}


#lang racket

(define (string-reverse s)
  (list->string (reverse (string->list s))))

(string-reverse "aoeu")


say "hello world".flip;
say "as⃝df̅".flip;
say 'ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧 👨👩👧👦🆗🗺'.flip;


begin
    % executes the procedure routine the specified number of times            %
    procedure repeat ( integer value count; procedure routine ) ;
        for i := 1 until count do routine;
    begin
        integer x;
        % print "hello" three times                                           %
        repeat( 3, write( "hello" ) );
        % print the first 10 squares                                          %
        write();
        x := 1;
        repeat( 10
              , begin
                    writeon( i_w := s_w := 1, x * x );
                    x := x + 1
                end
              )
    end
end.


-- applyN :: Int -> (a -> a) -> a -> a
on applyN(n, f, x)
    script go
        on |λ|(a, g)
            |λ|(a) of mReturn(g)
        end |λ|
    end script
    foldl(go, x, replicate(n, f))
end applyN

-------- SAMPLE FUNCTIONS FOR REPEATED APPLICATION --------

on double(x)
    2 * x
end double

on plusArrow(s)
    s & " -> "
end plusArrow

on squareRoot(n)
    n ^ 0.5
end squareRoot

-------------------------- TESTS --------------------------
on run
    log applyN(10, double, 1)
    --> 1024

    log applyN(5, plusArrow, "")
    --> " ->  ->  ->  ->  -> "

    log applyN(3, squareRoot, 65536)
    --> 4.0
end run

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

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

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

-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
    set out to {}
    if 1 > n then return out
    set dbl to {a}

    repeat while (1 < n)
        if 0 < (n mod 2) then set out to out & dbl
        set n to (n div 2)
        set dbl to (dbl & dbl)
    end repeat
    return out & dbl
end replicate


$ write sys$output f$fao( "!AS!-!AS!-!AS!-!AS!-!AS", "ha" )
$ write sys$output f$fao( "!12*d" )


repeat("fMsgBox",3)
return

repeat(f, n){
	loop % n
		%f%()
}

fMsgBox(){
	MsgBox hello
}


# syntax: GAWK -f REPEAT.AWK
BEGIN {
    for (i=0; i<=3; i++) {
      f = (i % 2 == 0) ? "even" : "odd"
      @f(i) # indirect function call
    }
    exit(0)
}
function even(n,  i) {
    for (i=1; i<=n; i++) {
      printf("inside even %d\n",n)
    }
}
function odd(n,  i) {
    for (i=1; i<=n; i++) {
      printf("inside odd %d\n",n)
    }
}


function RepeatString(const s: string; count: cardinal): string;
var
  i: Integer;
begin
  for i := 1 to count do
    Result := Result + s;
end;

Writeln(RepeatString('ha',5));


let rev_string = (s) => {
  let len = Js.String2.length(s)
  let arr = []
  for i in 0 to (len-1) {
    let c = Js.String2.get(s, len - 1 - i)
    let _ = Js.Array2.push(arr, c)
  }
  Js.String2.concatMany("", arr)
}

Js.log(rev_string("abcdefg"))


@echo off

:_main
setlocal
call:_func1 _func2 3
pause>nul
exit/b

:_func1
setlocal enabledelayedexpansion
for /l %%i in (1,1,%2) do call:%1
exit /b

:_func2
setlocal
echo _func2 has been executed
exit /b


•Show {2+𝕩}⍟3 1

_repeat_ ← {(𝕘>0)◶⊢‿(𝔽_𝕣_(𝕘-1)𝔽)𝕩}

•Show {2+𝕩} _repeat_ 3 1


#include <stdio.h>

void repeat(void (*f)(void), unsigned int n) {
 while (n-->0)
  (*f)(); //or just f()
}

void example() {
 printf("Example\n");
}

int main(int argc, char *argv[]) {
 repeat(example, 4);
 return 0;
}


using System;

namespace Repeat {
    class Program {
        static void Repeat(int count, Action<int> fn) {
            if (null == fn) {
                throw new ArgumentNullException("fn");
            }
            for (int i = 0; i < count; i++) {
                fn.Invoke(i + 1);
            }
        }

        static void Main(string[] args) {
            Repeat(3, x => Console.WriteLine("Example {0}", x));
        }
    }
}


IMPORT STD; //Imports the Standard Library

STRING MyBaseString := 'abc';
RepeatedString := STD.Str.Repeat(MyBaseString,3);
RepeatedString;  //returns 'abcabcabc'


/*REXX program to reverse a string  (and show before and after strings).*/

string1 = 'A man, a plan, a canal, Panama!'
string2 = reverse(string1)

say ' original string: '  string1
say ' reversed string: '  string2
                                       /*stick a fork in it, we're done.*/


cStr = "asdf"  cStr2 = ""
for x = len(cStr) to 1 step -1 cStr2 += cStr[x] next
See cStr2  # fdsa


template <typename Function>
void repeat(Function f, unsigned int n) {
 for(unsigned int i=n; 0<i; i--)
  f();
}


(defn repeat-function [f n]
  (dotimes [i n] (f)))


(defun repeat (f n)
  (dotimes (i n) (funcall f)))

(repeat (lambda () (format T "Example~%")) 5)


include "cowgol.coh";

# Only functions that implement an interface can be passed around
# The interface is a type and must be defined before it is used
# This defines an interface for a function that takes no arguments
interface Fn();

# This function repeats a function that implements Fn
sub Repeat(f: Fn, n: uint32) is
    while n != 0 loop
        f();
        n := n - 1;
    end loop;
end sub;

# Here is a function
sub Foo implements Fn is
    print("foo ");
end sub;

# Prints "foo foo foo foo"
Repeat(Foo, 4);
print_nl();


void repeat(void function() fun, in uint times) {
    foreach (immutable _; 0 .. times)
        fun();
}

void procedure() {
    import std.stdio;
    "Example".writeln;
}

void main() {
    repeat(&procedure, 3);
}


 repeat_string(a_string: STRING; times: INTEGER): STRING
 require
   times_positive: times > 0
 do
   Result := a_string.multiply(times)
 end


import system'routines;
import extensions;
import extensions'text;

public program()
{
    var s := new Range(0, 5).selectBy:(x => "ha").summarize(new StringWriter())
}


>> x = "rosettacode"
rosettacode

// script
rx = "";
for (i in strlen(x):1:-1)
{
  rx = rx + substr(x, i);
}

>> rx
edocattesor


. "local1 = Main string"
. "local2 = Temporary string storage"
. "local3 = String length"
set "$local1" to ""
set "$local2 " to ""
set "local3" to 0

input string "String to reverse:"
set "$local1" to "&INPUT&"
set "$local2" to "$local1"
set "local3" to "$local2.length"
loop start
set "$local1.(('local3' - 1) - 'loopcount')" to "$local2.('loopcount')"
loop for "('local3' - 1)"
* "Reversed string: &$local1& (Length: &$local1.length&)"
end


program Repeater;

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

type
  TSimpleProc = procedure;     // Can also define types for procedures (& functions) which
                               // require params.

procedure Once;
begin
  writeln('Hello World');
end;

procedure Iterate(proc : TSimpleProc; Iterations : integer);
var
  i : integer;
begin
  for i := 1 to Iterations do
    proc;
end;

begin
  Iterate(Once, 3);
  readln;
end.


(define (repeat f n) (for ((i n)) (f)))

(repeat (lambda () (write (random 1000))) 5)
    → 287 798 930 989 794

;; Remark
;; It is also possible to iterate a function : f(f(f(f( ..(f x)))))
(define cos10 (iterate cos 10)
(define cos100 (iterate cos10 10))
(cos100 0.6)
    →  0.7390851332151605
(cos 0.7390851332151605)
    → 0.7390851332151608 ;; fixed point found


open System

let Repeat c f =
    for _ in 1 .. c do
        f()

let Hello _ =
    printfn "Hello world"

[<EntryPoint>]
let main _ =
    Repeat 3 Hello

    0 // return an integer exit code


repeat(X,N) ->
    lists:flatten(lists:duplicate(N,X)).


PROCEDURE REPEAT_STRING(S$,N%->REP$)
   LOCAL I%
   REP$=""
   FOR I%=1 TO N% DO
       REP$=REP$+S$
   END FOR
END PROCEDURE


string$ = "123456789abcdefghijk"
for i = len(string$) to 1 step -1
 print mid$(string$,i,1);
next i


let mut buffer = b"abcdef".to_vec();
buffer.reverse();
assert_eq!(buffer, b"fedcba");


variable sa = "Hello, World", aa = Char_Type[strlen(sa)+1];
init_char_array(aa, sa);
array_reverse(aa);
% print(aa);

% Unfortunately, strjoin() only joins strings, so we map char()
% [sadly named: actually converts char into single-length string]
% onto the array:

print( strjoin(array_map(String_Type, &char, aa), "") );


: times ( xt n -- )
  0 ?do dup execute loop drop ;


' FB 1.05.0 Win64

Sub proc()
  Print " proc called"
End Sub

Sub repeat(s As Sub, n As UInteger)
  For i As Integer = 1 To n
    Print Using "##"; i;
    s()
  Next
End Sub

repeat(@proc, 5)
Print
Print "Press any key to quit"
Sleep


Public Sub Main()

    RepeatIt("RepeatableOne", 2)

    RepeatIt("RepeatableTwo", 3)

End

'Cannot pass procedure pointer in Gambas; must pass procedure name and use Object.Call()
Public Sub RepeatIt(sDelegateName As String, iCount As Integer)

    For iCounter As Integer = 1 To iCount
        Object.Call(Me, sDelegateName, [])
    Next

End

Public Sub RepeatableOne()

    Print "RepeatableOne"

End

Public Sub RepeatableTwo()

    Print "RepeatableTwo"

End


package main

import "fmt"

func repeat(n int, f func()) {
  for i := 0; i < n; i++ {
    f()
  }
}

func fn() {
  fmt.Println("Example")
}

func main() {
  repeat(4, fn)
}


sequence s = ""
for i = 1 to 5 do s &= "ha" end for
puts(1,s)

hahahahaha


> String.replicate 5 "ha";;
val it : string = "hahahahaha"


data _null_;
length a b $11;
a="I am Legend";
b=reverse(a);
put a;
put b;
run;


class MAIN is
  main is
    s ::= "asdf";
    reversed ::= s.reverse;
    -- current implementation does not handle multibyte encodings correctly
  end;
end;


import Control.Monad (replicateM_)

sampleFunction :: IO ()
sampleFunction = putStrLn "a"

main = replicateM_ 5 sampleFunction


theory Scratch
  imports Main
begin

text‹
Given the function we want to execute multiple times is of
type \<^typ>‹unit ⇒ unit›.
›
fun pure_repeat :: "(unit ⇒ unit) ⇒ nat ⇒ unit" where
  "pure_repeat _ 0 = ()"
| "pure_repeat f (Suc n) = f (pure_repeat f n)"

text‹
Functions are pure in Isabelle. They don't have side effects.
This means, the \<^const>‹pure_repeat› we implemented is always equal
to \<^term>‹() :: unit›, independent of the function \<^typ>‹unit ⇒ unit›
or \<^typ>‹nat›.
Technically, functions are not even "executed", but only evaluated.
›
lemma "pure_repeat f n = ()" by simp

text‹
But we can repeat a value of \<^typ>‹'a› \<^term>‹n› times and return the result
in a list of length \<^term>‹n›
›
fun repeat :: "'a ⇒ nat ⇒ 'a list" where
  "repeat _ 0 = []"
| "repeat f (Suc n) = f # (repeat f n)"

lemma "repeat ''Hello'' 4 = [''Hello'', ''Hello'', ''Hello'', ''Hello'']"
  by code_simp

lemma "length (repeat a n) = n" by(induction n) simp+

text‹
Technically, \<^typ>‹'a› is not a function. We can wrap it in a dummy function
which takes a \<^typ>‹unit› as first argument. This gives a function of type
\<^typ>‹unit ⇒ 'a›.
›

fun fun_repeat :: "(unit ⇒ 'a) ⇒ nat ⇒ 'a list" where
  "fun_repeat _ 0 = []"
| "fun_repeat f (Suc n) = (f ()) # (fun_repeat f n)"

lemma "fun_repeat (λ_. ''Hello'') 4 =
       [''Hello'', ''Hello'', ''Hello'', ''Hello'']"
  by code_simp

text‹
Yet, \<^const>‹fun_repeat› with the dummy function \<^typ>‹unit ⇒ 'a› is
equivalent to \<^const>‹repeat› with the value \<^typ>‹'a› directly.
›
lemma "fun_repeat (λ_. a) n = repeat a n" by(induction n) simp+

end


   NB. ^: (J's power conjunction) repeatedly evaluates a verb.

   NB. Appending to a vector the sum of the most recent
   NB. 2 items can generate the Fibonacci sequence.

   (, [: +/ _2&{.)  (^:4)  0 1
0 1 1 2 3 5

   NB. Repeat an infinite number of times
   NB. computes the stable point at convergence

   cosine =: 2&o.

   cosine (^:_ ) 2    NB. 2 is the initial value
0.739085

   cosine 0.739085  NB. demonstrate the stable point x==Cos(x)
0.739085

   cosine^:(<_) 2  NB. show the convergence
2 _0.416147 0.914653 0.610065 0.819611 0.682506 0.775995 0.713725 0.755929 0.727635 0.74675 0.733901 0.742568 0.736735 0.740666 0.738019 0.739803 0.738602 0.739411 0.738866 0.739233 0.738986 0.739152 0.73904 0.739116 0.739065 0.739099 0.739076 0.739091 0.7...

   # cosine^:(<_) 2  NB. iteration tallyft
78

   f =: 3 :'smoutput ''hi'''

   f''
hi

   NB. pass verbs via a gerund
   repeat =: dyad def 'for_i. i.y do. (x`:0)0 end. EMPTY'

   (f`'')repeat 4
hi
hi
hi
hi

   NB. pass a verb directly to an adverb

   Repeat =: adverb def 'for_i. i.y do. u 0 end. EMPTY'

   f Repeat 4
hi
hi
hi
hi


import java.util.function.Consumer;
import java.util.stream.IntStream;

public class Repeat {

    public static void main(String[] args) {
        repeat(3, (x) -> System.out.println("Example " + x));
    }

    static void repeat (int n, Consumer<Integer> fun) {
        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));
    }
}


: repeat-string ( str n -- str' ) swap <repetition> concat ;

"ha" 5 repeat-string print


: place-n { src len dest n -- }
  0 dest c!
  n 0 ?do src len dest +place loop ;

s" ha" pad 5 place-n
pad count type    \ hahahahaha


program test_repeat

  write (*, '(a)') repeat ('ha', 5)

end program test_repeat


(define (string-reverse s)
  (list->string (reverse (string->list s))))


#!/bin/sed -f

/../! b

# Reverse a line.  Begin embedding the line between two newlines
s/^.*$/\
&\
/

# Move first character at the end.  The regexp matches until
# there are zero or one characters between the markers
tx
:x
s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/
tx

# Remove the newline markers
s/\n//g


def unoptimized_repeat(f; n):
  if n <= 0 then empty
  else f, repeat(f; n-1)
  end;


function sayHi()
	println("Hi")
end

function rep(f, n)
	for i = 1:n f() end
end

rep(sayHi, 3)


// version 1.0.6

fun repeat(n: Int, f: () -> Unit) {
    for (i in 1..n) {
        f()
        println(i)
    }
}

fun main(args: Array<String>) {
    repeat(5) { print("Example ") }
}


def repeat : ℕ → (ℕ → string) → string
  | 0 f       := "done"
  | (n + 1) f :=  (f n) ++ (repeat n f)

#eval repeat 5 $ λ b : ℕ , "me "


rep "answer",3

command rep x,n
    repeat n times
        do merge("[[x]] [[n]]")
    end repeat
end rep


function myFunc ()
    print("Sure looks like a function in here...")
end

function rep (func, times)
    for count = 1, times do
        func()
    end
end

rep(myFunc, 4)


' FB 1.05.0 Win64

' A character is essentially a string of length 1 in FB though there is a built-in function, String,
' which creates a string by repeating a character a given number of times.

' To avoid repeated concatenation (a slow operation) when the string to be repeated has a length
' greater than one, we instead create a buffer of the required size and then fill that.

Function repeat(s As String, n As Integer) As String
  If n < 1 Then Return ""
  If n = 1 Then Return s
  Var size = Len(s)
  If size = 0 Then Return s  ' empty string
  If size = 1 Then Return String(n, s[0])  ' repeated single character
  Var buffer = Space(size * n)  'create buffer for size > 1
  For i As Integer = 0 To n - 1
    For j As Integer = 0 To size - 1
      buffer[i * size + j] = s[j]
    Next j
  Next i
  Return buffer
End Function

Print repeat("rosetta", 1)
Print repeat("ha", 5)
Print repeat("*", 5)
Print
Print "Press any key to quit program"
Sleep


$ include "seed7_05.s7i";

const func string: reverse (in string: stri) is func
  result
    var string: result is "";
  local
    var integer: index is 0;
  begin
    for index range length(stri) downto 1 do
      result &:= stri[index];
    end for;
  end func;

const proc: main is func
  begin
    writeln(reverse("Was it a cat I saw"));
  end func;


put "asdf" reversed -- reverse on the fly

set imp to "rumpelstiltskin"
reverse imp -- reverse in place
put imp


repeat[f_, n_] := Do[f[], {n}];
repeat[Print["Hello, world!"] &, 5];


sayHi = function()
    print "Hi!"
end function

rep = function(f, n)
    for i in range(1, n)
        f
    end for
end function

rep @sayHi, 3


MODULE Repeat;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

TYPE F = PROCEDURE;

PROCEDURE Repeat(fun : F; c : INTEGER);
VAR i : INTEGER;
BEGIN
    FOR i:=1 TO c DO
        fun
    END
END Repeat;

PROCEDURE Print;
BEGIN
    WriteString("Hello");
    WriteLn
END Print;

BEGIN
    Repeat(Print, 3);

    ReadChar
END Repeat.


def repeat(f,n)
    for i in range(1, n)
        f()
    end
end

def procedure()
    println "Example"
end

repeat(procedure, 3)


Public Sub Main()

Print String$(5, "ha")

End


Concatenation(ListWithIdenticalEntries(10, "BOB "));
"BOB BOB BOB BOB BOB BOB BOB BOB BOB BOB "


fmt.Println(strings.Repeat("ha", 5))        // ==> "hahahahaha"


import <Utilities/Sequence.sl>;

main(args(2)) := Sequence::reverse(args[1]);


"asdf".reverse;             # fdsa
"résumé niño".reverse;      # oñin émusér


BEGIN
   TEXT PROCEDURE REV(S); TEXT S;
   BEGIN
       TEXT T;
       INTEGER L,R;
       T :- COPY(S);
       L := 1; R := T.LENGTH;
       WHILE L < R DO
       BEGIN
           CHARACTER CL,CR;
           T.SETPOS(L); CL := T.GETCHAR;
           T.SETPOS(R); CR := T.GETCHAR;
           T.SETPOS(L); T.PUTCHAR(CR);
           T.SETPOS(R); T.PUTCHAR(CL);
           L := L+1;
           R := R-1;
        END;
        REV :- T;
   END REV;

   TEXT INP;
   INP :- "asdf";

   OUTTEXT(INP);      OUTIMAGE;
   OUTTEXT(REV(INP)); OUTIMAGE;
END


proc example =
  echo "Example"

# Ordinary procedure
proc repeatProc(fn: proc, n: int) =
  for x in 0..<n:
    fn()

repeatProc(example, 4)

# Template (code substitution), simplest form of metaprogramming
# that Nim has
template repeatTmpl(n: int, body: untyped): untyped =
  for x in 0..<n:
    body

# This gets rewritten into a for loop
repeatTmpl 4:
  example()

import std/macros
# A macro which takes some code block and returns code
# with that code block repeated n times. Macros run at
# compile-time
macro repeatMacro(n: static[int], body: untyped): untyped =
  result = newStmtList()

  for x in 0..<n:
    result.add body

# This gets rewritten into 4 calls to example()
# at compile-time
repeatMacro 4:
  example()


class Repeat {
  function : Main(args : String[]) ~ Nil {
    Repeat(Example() ~ Nil, 3);
  }

  function : Repeat(e : () ~ Nil, i : Int) ~ Nil {
    while(i-- > 0) {
      e();
    };
  }

  function : Example() ~ Nil {
    "Example"->PrintLine();
  }
}


let repeat ~f ~n =
  for i = 1 to n do
    f ()
  done

let func () =
  print_endline "Example"

let () =
  repeat ~n:4 ~f:func


: hello "Hello, World!" println ;
10 #hello times


CHARACTER out*20

EDIT(Text=out, Insert="ha", DO=5)


repeat(f, n)=for(i=1,n,f());
repeat( ()->print("Hi!"), 2);


program Repeater;

type
  TProc = procedure(I: Integer);

procedure P(I: Integer);
begin
  WriteLn('Iteration ', I);
end;

procedure Iterate(P: TProc; N: Integer);
var
  I: Integer;
begin
  for I := 1 to N do
    P(I);
end;

begin
  Iterate(P, 3);
end.


sub repeat {
    my ($sub, $n) = @_;
    $sub->() for 1..$n;
}

sub example {
    print "Example\n";
}

repeat(\&example, 4);


procedure Repeat(integer rid, integer n)
    for i=1 to n do
        rid()
    end for
end procedure

procedure Hello()
    ?"Hello"
end procedure

Repeat(Hello,5)


procedure main(args)
    write(repl(integer(!args) | 5))
end


strRepeat : Nat -> String -> String
strRepeat Z s = ""
strRepeat (S n) s = s ++ strRepeat n s

chrRepeat : Nat -> Char -> String
chrRepeat Z c = ""
chrRepeat (S n) c = strCons c $ chrRepeat n c


Home is a room.

To decide which indexed text is (T - indexed text) repeated (N - number) times:
	let temp be indexed text;
	repeat with M running from 1 to N:
		let temp be "[temp][T]";
	decide on temp.

When play begins:
	say "ha" repeated 5 times;
	end the story.


 10 PRINT STRING$("ha",5)
100 DEF STRING$(S$,N)
105   LET ST$=""
110   FOR I=1 TO N
120     LET ST$=ST$&S$
130   NEXT
140   LET STRING$=ST$
150 END DEF


	output = reverse(reverse("reverse"))
end


val str_reverse = implode o rev o explode;
val string = "asdf";
val reversed = str_reverse string;


. scalar s="ARS LONGA VITA BREVIS"
. di strreverse(s)
SIVERB ATIV AGNOL SRA
. scalar s="Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν"
. di ustrreverse(s)
νῆγ νὴτ ὶακ νὸναρὐο νὸτ ςὸεθ ὁ νεσηίοπἐ ῇχρἀ νἘ


def myFunc
    "Sure looks like a function in here..." print nl
enddef

def rep /# func times -- #/
    for drop
	dup exec
    endfor
    drop
enddef

getid myFunc 4 rep


# The built-in function "do" can be used to achieve our goal,
# however, it has a slightly different syntax than what the
# problem specifies.

# Native solution.
(do 10 (version))

# Our solution.
(de dofn (Fn N)
   (do N (Fn)) )

(dofn version 10)


function Out-Example
{
    "Example"
}

function Step-Function ([string]$Function, [int]$Repeat)
{
    for ($i = 1; $i -le $Repeat; $i++)
    {
        "$(Invoke-Expression -Command $Function) $i"
    }
}

Step-Function Out-Example -Repeat 3


repeat(_, 0).
repeat(Callable, Times) :-
	succ(TimesLess1, Times),
	Callable,
	repeat(Callable, TimesLess1).

test :- write('Hello, World'), nl.
test(Name) :- format('Hello, ~w~n', Name).


Prototype.i fun(x.i)

Procedure.i quark(z.i)
  Debug "Quark "+Str(z) : ProcedureReturn z-1
EndProcedure

Procedure rep(q.fun,n.i)
  Repeat : n=q(n) : Until n=0
EndProcedure

rep(@quark(),3)


   5 # '*'               NB. repeat each item 5 times
*****
   5 # 'ha'              NB. repeat each item 5 times
hhhhhaaaaa
   5 ((* #) $ ]) 'ha'    NB. repeat array 5 times
hahahahaha
   5 ;@# < 'ha'          NB. using boxing to treat the array as a whole
hahahahaha


public static String repeat(String str, int times) {
    StringBuilder sb = new StringBuilder(str.length() * times);
    for (int i = 0; i < times; i++)
        sb.append(str);
    return sb.toString();
}

public static void main(String[] args) {
    System.out.println(repeat("ha", 5));
}


String.prototype.repeat = function(n) {
    return new Array(1 + (n || 0)).join(this);
}

console.log("ha".repeat(5));  // hahahahaha


func reverseString(s: String) -> String {
  return String(s.characters.reverse())
}
print(reverseString("asdf"))
print(reverseString("as⃝df̅"))


| reverse string

c : 'abcdefghijklmnopqrstuvwxyz'
d : ' '

 c []
 i
 #c j
 - j
 if i < j
    c.i d 1
    c.j c.i 1
    d c.j
    - j
    + i
    goif
 endif
 c []


templates reverse
  '$:[ $... ] -> $(last..first:-1)...;' !
end reverse

'asdf' -> reverse -> !OUT::write

'
' -> !OUT::write

'as⃝df̅' -> reverse -> !OUT::write


#!/usr/bin/python
def repeat(f,n):
  for i in range(n):
    f();

def procedure():
  print("Example");

repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines.


  [ stack ]                     is times.start  (     --> s   )
  protect times.start

  [ stack ]                     is times.count  (     --> s   )
  protect times.count

  [ stack ]                     is times.action (     --> s   )
  protect times.action

  [ ]'[ times.action put
    dup times.start put
    [ 1 - dup -1 > while
      times.count put
      times.action share do
      times.count take again ]
    drop
    times.action release
    times.start release ]       is times         (   n -->   )

  [ times.count share ]         is i             (     --> n )

  [ times.start share i 1+ - ]  is i^            (     --> n )

  [ 0 times.count replace ]     is conclude      (     -->   )

  [ times.start share
    times.count replace ]       is refresh       (     -->   )

  [ times.count take 1+
    swap - times.count put ]    is step          (     --> s )

  [ nested ' times nested
    swap join do ]              is rosetta-times ( n x -->   )


f1 <- function(...){print("coucou")}

f2 <-function(f,n){
lapply(seq_len(n),eval(f))
}

f2(f1,4)


#lang racket/base
(define (repeat f n) ; the for loop is idiomatic of (although not exclusive to) racket
  (for ((_ n)) (f)))

(define (repeat2 f n) ; This is a bit more "functional programmingy"
  (when (positive? n) (f) (repeat2 f (sub1 n))))

(display "...")
(repeat (λ () (display " and over")) 5)
(display "...")
(repeat2 (λ () (display " & over")) 5)
(newline)


sub repeat (&f, $n) { f() xx $n };

sub example { say rand }

repeat(&example, 3);


Red[]

myrepeat: function [fn n] [loop n [do fn]]

myrepeat [print "hello"] 3


@show "ha" ^ 5

# The ^ operator is really just call to the `repeat` function
@show repeat("ha", 5)


fun main(args: Array<String>) {
    println("ha".repeat(5))
}


LDA #<foo
sta $00
LDA #>foo
sta $01
jsr PrintBytecode

foo:
;do stuff
rts

PrintBytecode:
ldy #0

lda $01     ;high byte of starting address of the source
jsr PrintHex
;unimplemented routine that separates the "nibbles" of the accumulator,
; adds $30 or $37 to each depending on if it's 0-9 or A-F respectively, which converts hex to ASCII,
; then prints the high nibble then the low.

lda $00      ;low byte of the starting address of the source
jsr PrintHex
jsr NewLine  ;unimplemented new line routine

loop:
lda ($00),y
cmp #$60
beq Terminated
jsr PrintHex

jmp loop
Terminated:
jsr PrintHex ;print the last instruction of the routine.
rts


; Use source function for source code.
(source println)

; Use meta function for filenames and line numbers (and other metadata)
(meta #'println)


USE: see
\ integer see ! class
nl
\ dip see     ! word


' FB 1.05.0 Win64 (getsource.bas)

Sub Proc()
  Print __Function__  & " is defined in " & __Path__ & "\" & __File__ & " at line " & ( __line__ - 1)
End Sub

Proc()
Sleep


package main

import (
    "fmt"
    "path"
    "reflect"
    "runtime"
)

func someFunc() {
    fmt.Println("someFunc called")
}

func main() {
    pc := reflect.ValueOf(someFunc).Pointer()
    f := runtime.FuncForPC(pc)
    name := f.Name()
    file, line := f.FileLine(pc)
    fmt.Println("Name of function :", name)
    fmt.Println("Name of file     :", path.Base(file))
    fmt.Println("Line number      :", line)
}


package require Tcl 8.5
string reverse asdf


:Str1
:For(I,1,length(Ans)-1
:sub(Ans,2I,1)+Ans
:End
:sub(Ans,1,I→Str1


prog:   parse(str);
str:    smark any(!<<>>) scopy str/done = { 1 2 };
done:   ;


/*REXX program   executes   a  named  procedure  a specified number of times.           */
parse arg pN # .                                 /*obtain optional arguments from the CL*/
if #=='' | #==","   then #= 1                    /*assume  once  if not specified.      */
if pN\==''          then call repeats pN, #      /*invoke the REPEATS procedure for  pN.*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
repeats: procedure;  parse arg x,n               /*obtain the procedureName & # of times*/
                do n;  interpret 'CALL' x;  end  /*repeat the invocation    N    times. */
         return                                  /*return to invoker of the REPEATS proc*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
yabba:   say 'Yabba, yabba do!';          return /*simple code;  no need for  PROCEDURE.*/


Func Main
     times(5,:test)

Func Test
     see "Message from the test function!" + nl

Func Times nCount, F
     for x = 1 to nCount
         Call F()
     next


4.times{ puts "Example" }  # idiomatic way

def repeat(proc,num)
  num.times{ proc.call }
end

repeat(->{ puts "Example" }, 4)


fn repeat(f: impl FnMut(usize), n: usize) {
    (0..n).for_each(f);
}


  def repeat[A](n:Int)(f: => A)= ( 0 until n).foreach(_ => f)

  repeat(3) { println("Example") }


(import (scheme base)
        (scheme write))

(define (repeat proc n)
  (do ((i 0 (+ 1 i))
       (res '() (cons (proc) res)))
    ((= i n) res)))

;; example returning an unspecified value
(display (repeat (lambda () (display "hi\n")) 4)) (newline)

;; example returning a number
(display (repeat (lambda () (+ 1 2)) 5)) (newline)


{S.map {lambda {_} ha} {S.serie 1 10}}
-> ha ha ha ha ha ha ha ha ha ha

or

{S.replace \s
        by
        in {S.map {lambda {_} ha}
                  {S.serie 1 10}}}
-> hahahahahahahahahaha

or

{def repeat
 {lambda {:w :n}
  {if {< :n 0}
   then
   else :w{repeat :w {- :n 1}}}}}
-> repeat

{repeat ha 10}
-> hahahahahahahahahahaha


   mean=:+/ %#
   5!:5 <'mean'
+/ % #
   5!:6 <'mean'
(+/) % #
   4!:4 <'mean'
_1
   4!:4 <'names'
2
   2 { 4!:3 ''
┌────────────────────────────────────────────┐
│/Applications/j64-804/system/main/stdlib.ijs│
└────────────────────────────────────────────┘


public class ReflectionGetSource {

    public static void main(String[] args) {
        new ReflectionGetSource().method1();

    }

    public ReflectionGetSource() {}

    public void method1() {
        method2();
    }

    public void method2() {
        method3();
    }

    public void method3() {
        Throwable t = new Throwable();
        for ( StackTraceElement ste : t.getStackTrace() ) {
            System.out.printf("File Name   = %s%n", ste.getFileName());
            System.out.printf("Class Name  = %s%n", ste.getClassName());
            System.out.printf("Method Name = %s%n", ste.getMethodName());
            System.out.printf("Line number = %s%n%n", ste.getLineNumber());
        }
    }

}


function foo() {...}
foo.toString();
// "function foo() {...}"


# Definition
function foo() end

@which foo() # where foo is defined
@less foo() # first file where foo is defined


// Kotlin JS Version 1.2.31

fun hello() {
    println("Hello")
}

fun main(args: Array<String>) {
    val code = js("_.hello.toString()")
    println(code)
}


----------------------------------------
-- Returns source code either for a class (parent script) or a class instance (object)
-- @param {script|instance} class
-- @return {string}
----------------------------------------
on getClassCode (class)
  if ilk(class)=#instance then class=class.script
  return class.text
end

----------------------------------------
-- Returns the source code of the movie script that defines the specified global function
-- @param {symbol} func - function specified as symbol
-- @return {string|VOID}
----------------------------------------
on getGlobalFunctionCode (func)
  -- iterate over all members in all castlibs
  repeat with i = 1 to _movie.castlib.count
    repeat with j = 1 to _movie.castlib[i].member.count
      m = _movie.castlib[i].member[j]
      if m.type<>#script then next repeat
      if m.scriptType=#movie and m.script.handler(func) then return m.script.text
    end repeat
  end repeat
end


when flag clicked
ask "Say something..." and wait
set i to (length of answer)
set inv to ""
repeat until i = 0
	set inv to (join (inv) (letter (i) of answer))
	change i by -1
end
say inv


#lang transd

MainModule : {
    _start: (lambda (with s "as⃝df̅"
        (textout (reverse s))

        // reversing user input
        (textout "\nPlease, enter a string: ")
        (textout "Input: " (reverse (read s)))
    ))
}


$ include "seed7_05.s7i";

const proc: myRepeat (in integer: times, in proc: aProcedure) is func
  local
    var integer: n is 0;
  begin
    for n range 1 to times do
      aProcedure;
    end for;
  end func;

const proc: main is func
  begin
    myRepeat(3, writeln("Hello!"));
  end func;


func repeat(f, n) {
    { f() } * n;
}

func example {
    say "Example";
}

repeat(example, 4);


fun repeat (_, 0) = ()
  | repeat (f, n) = (f (); repeat (f, n - 1))

fun testProcedure () =
  print "test\n"

val () = repeat (testProcedure, 5)


function repeat(f,n) {
	for (i=1; i<=n; i++) (*f)()
}

function hello() {
	printf("Hello\n")
}

repeat(&hello(),3)


func repeat(n: Int, f: () -> ()) {
  for _ in 0..<n {
    f()
  }
}

repeat(4) { println("Example") }


proc repeat {command count} {
    for {set i 0} {$i < $count} {incr i} {
        uplevel 1 $command
    }
}

proc example {} {puts "This is an example"}
repeat example 4


Proc _Repeat (_HelloWorld, 5) : End

_Repeat Param (2) : Local (1) : For [email protected] = 1 To [email protected] : Proc [email protected] : Next : Return
_HelloWorld Print "Hello world!" : Return


a$ ="ha "
print StringRepeat$( a$, 5)

end

function StringRepeat$( in$, n)
    o$ =""
    for i =1 to n
        o$ =o$ +in$
    next i
    StringRepeat$ =o$
end function


debug = require("debug")
function foo(bar)
  info = debug.getinfo(1)
  for k,v in pairs(info) do print(k,v) end
end
foo()


import Nanoquery.IO
println new(File, __file__).readAll()


import macros, strformat

proc f(arg: int): int = arg+1

macro getSource(source: static[string]) =
  let module = parseStmt(source)
  for node in module.children:
    if node.kind == nnkProcDef:
      echo(&"source of procedure {node.name} is:\n{toStrLit(node).strVal}")

proc g(arg: float): float = arg*arg

getSource(staticRead(currentSourcePath()))


# 20211213 Perl programming solution

use strict;
use warnings;

use Class::Inspector;

print Class::Inspector->resolved_filename( 'IO::Socket::INET' ), "\n";


    {"C:\\Program Files (x86)\\Phix\\builtins\\",
     "C:\\Program Files (x86)\\Phix\\builtins\\VM\\",
     "C:\\Program Files (x86)\\Phix\\"}


import os
os.__file__
# "/usr/local/lib/python3.5/os.pyc"


say &sum.file;
say Date.^find_method("day-of-week").file;


/*REXX program gets the source function (source code) and */
/*───────────────────────── displays the number of lines. */
#=sourceline()
                do j=1  for sourceline()
                say 'line'  right(j, length(#) )  '──►'   ,
                            strip( sourceline(j), 'T')
                end   /*j*/
say
parse source x y sID
say  'The name of the  source file (program) is: '    sID
say  'The number of lines in the source program: '     #
                     /*stick a fork in it, we're all done.*/


# Project : Reflection/Get source

fp = fopen("C:\Ring\applications\fifteenpuzzle\CalmoSoftFifteenPuzzleGame.ring","r")
r = ""
str = ""
flag = 0
numline = 0
see "give the function: "
give funct
funct = "func " + funct
while isstring(r)
        r = fgetc(fp)
        if r = char(10)
           flag = 1
           numline = numline + 1
        else
           flag = 0
           str = str + r
        ok
        if flag = 1
           if left(str,len(funct)) = funct
              see '"' + funct + '"' +" is in the line: " + numline + nl
           ok
           str = ""
        ok
end
fclose(fp)


require 'mathn'
Math.method(:sqrt).source_location
# ["/usr/local/lib/ruby2.3/2.3.0/mathn.rb", 119]

Class.method(:nesting).source_location
# nil, since Class#nesting is native


function reverse (s : string) : string
    var rs := ""
    for i : 0 .. length (s) - 1
        rs := rs + s (length (s) - i)
    end for
    result rs
end reverse

put reverse ("iterative example")
put reverse (reverse ("iterative example"))


$$ MODE TUSCRIPT
SET input="was it really a big fat cat i saw"
SET reversetext=TURN (input)
PRINT "before: ",input
PRINT "after:  ",reversetext


#!/bin/bash
str=abcde

for((i=${#str}-1;i>=0;i--)); do rev="$rev${str:$i:1}"; done

echo $rev


def repeat (function f, int n)
	for (set n n) (> n 0) (dec n)
		f
	end for
end repeat

def procedure ()
	out "Hello! " console
end procedure

# outputs "Hello! " 5 times
repeat procedure 5


Private Sub Repeat(rid As String, n As Integer)
    For i = 1 To n
        Application.Run rid
    Next i
End Sub

Private Sub Hello()
    Debug.Print "Hello"
End Sub

Public Sub main()
    Repeat "Hello", 5
End Sub


module main;
    initial begin
        repeat(5) begin
            $display("Inside loop");
        end
        $display("Loop Ended");
    end
endmodule


Module Module1

    Sub Repeat(count As Integer, fn As Action(Of Integer))
        If IsNothing(fn) Then
            Throw New ArgumentNullException("fn")
        End If

        For i = 1 To count
            fn.Invoke(i)
        Next
    End Sub

    Sub Main()
        Repeat(3, Sub(x) Console.WriteLine("Example {0}", x))
    End Sub

End Module


fn repeat(n int, f fn()) {
  for _ in 0.. n {
    f()
  }
}

fn func() {
  println("Example")
}

fn main() {
  repeat(4, func)
}


var f = Fn.new { |g, n|
    for (i in 1..n) g.call(n)
}

var g = Fn.new { |k|
    for (i in 1..k) System.write("%(i) ")
    System.print()
}

f.call(g, 5)


on rep (str, n)
  res = ""
  repeat with i = 1 to n
    put str after res
  end repeat
  return res
end


on mouseUp
    put repeatString("ha", 5)
end mouseUp

function repeatString str n
    repeat n times
        put str after t
    end repeat
    return t
end repeatString


to copies :n :thing [:acc "||]
  if :n = 0 [output :acc]
  output (copies :n-1 :thing combine :acc :thing)
end


mthd := someClass compiledMethodAt:#nameOfMethod


proc getproc {name} {
    set name [uplevel 1 [list namespace which -command $name]]
    set args [info args $name]
    set args [lmap arg $args {  ;# handle default arguments, if it has them!
        if {[info default $name $arg default]} {
            list $name $default
        } else {
            return -level 0 $arg
        }
    }]
    set body [info body $name]
    list proc $name $args $body
}

puts [getproc getproc]


import "os" for Platform, Process
import "io" for File
import "/pattern" for Pattern

var getSourceLines = Fn.new {
    var fileName = Process.allArguments[1]
    var text = File.read(fileName)
    var sep = Platform.isWindows ? "\r\n" : "\n"
    return [fileName, text.split(sep)]
}

var res = getSourceLines.call()
var fileName = res[0]
var lines = res[1]
// look for getSourceLines function
var funcName = "getSourceLines"
var p = Pattern.new("+1/s")
var i = 1
var found = 0
for (line in lines) {
    var t = p.splitAll(line.trim())
    if (t[0] == "var" && t[1] == funcName && t[2] == "=" && t[3] == "Fn.new") {
        found = i
        break
    }
    i = i + 1
}

System.print("File name     : %(fileName)")
System.print("Function name : %(funcName)")
System.print("Line number   : %(found > 0 ? found : "Function not found")")


src:=File(__FILE__).read();
println("Src file is \"%s\" and has %d lines".fmt(__FILE__,src.len(1)));


#import std

#cast %s

example = ~&x 'asdf'

verbose_example = reverse 'asdf'


int main (string[] args) {
	if (args.length < 2) {
		stdout.printf ("Please, input a string.\n");
		return 0;
	}
	var str = new StringBuilder ();
	for (var i = 1; i < args.length; i++) {
		str.append (args[i] + " ");
	}
	stdout.printf ("%s\n", str.str.strip ().reverse ());
	return 0;
}


func rep(callback:function,amount:number,*args:array=[]):null{
	repeat amount {
		callback(*args);
	}
}

rep(func(a,b,c){
	log(a+b+c);
},3,1,2,3);


(defun repeat (f n)
    (f)
    (if (> n 1)
        (repeat f (- n 1)) ) )

;; an example to test it:
(repeat (lambda () (print '(hello rosetta code))) 5)


sub myFunc ()
    print "Sure looks like a function in here..."
end sub

sub rep (func$, times)
    for count = 1 to times
        execute(func$)
    next
end sub

rep("myFunc", 4)


ld b,&05  ;load the decrement value into b
ld hl,myFunc ;load the address of "myFunc" into HL

call repeatProcedure

forever:
jp forever ;trap the program counter here

repeatProcedure: ;input: b = times to repeat, hl = which procedure to repeat
call trampoline
; the "ret" in myFunc will bring you here
djnz repeatProcedure
ret ;exit "repeatProcedure" and proceed to "forever"

trampoline:
push hl
ret
;this is effectively a call to whatever is in HL, in this case "myFunc." The "ret" at the end of myFunc will return us to
;just after the line "call trampoline"

myFunc: ;this doesn't do anything useful but that's not the point
push hl ;not needed for this routine but if it altered HL we would need this so that we come back here next time we loop
or a
pop hl
ret


fcn repeat(f,n){ do(n){ f() } }
repeat("ho ".print,3);


function repeats(s, n) return n > 0 and s .. repeats(s, n-1) or "" end


> use StringTools in
>       Repeat( "abc", 10 ); # repeat an arbitrary string
>       Fill( "x", 20 )      # repeat a character
> end use;
                    "abcabcabcabcabcabcabcabcabcabc"

                         "xxxxxxxxxxxxxxxxxxxx"


(* solution 1 *)
rep[n_Integer,s_String]:=Apply[StringJoin,ConstantArray[s,{n}]]
(* solution 2 -- @@ is the infix form of Apply[] *)
rep[n_Integer,s_String]:[email protected]@Table[s,{n}]
(* solution 3 -- demonstrating another of the large number of looping constructs available *)
rep[n_Integer,s_String]:=Nest[StringJoin[s, #] &,s,n-1]


Public Function Reverse(aString as String) as String
' returns the reversed string
dim L as integer        'length of string
dim newString as string

newString = ""
L = len(aString)
for i = L to 1 step -1
 newString = newString & mid$(aString, i, 1)
next
Reverse = newString
End Function


Reg_Empty(10)
for (BOL; !At_EOL; Char) {
    Reg_Copy_Block(10, CP, CP+1, INSERT)
}


function S = repeat(s , n)
    S = repmat(s , [1,n]) ;
return


"$*"(s, n) := apply(sconcat, makelist(s, n))$
infix("$*")$

"abc" $* 5;
/* "abcabcabcabcabc" */


:- module repeat.
:- interface.
:- import_module string, char, int.

:- func repeat_char(char, int) = string.
:- func repeat(string, int) = string.

:- implementation.
:- import_module stream, stream.string_writer, string.builder.

repeat_char(C, N) = string.duplicate_char(C, N).

repeat(String, Count) = Repeated :-
        S0 = string.builder.init,
        Repeated = string.builder.to_string(S),
        printn(string.builder.handle, Count, String, S0, S).

:- pred printn(Stream, int, string, State, State)
               <= (stream.writer(Stream, string, State),
                   stream.writer(Stream, character, State)).
:- mode printn(in, in, in, di, uo) is det.
printn(Stream, N, String, !S) :-
        ( N > 0 ->
                print(Stream, String, !S),
                printn(Stream, N - 1, String, !S)
        ; true ).


#Const REDIRECTOUT = True

Module Program
    Const OUTPATH = "out.txt"

    ReadOnly TestCases As String() = {"asdf", "as⃝df̅", "Les Misérables"}

    ' SIMPLE VERSION
    Function Reverse(s As String) As String
        Dim t = s.ToCharArray()
        Array.Reverse(t)
        Return New String(t)
    End Function

    ' EXTRA CREDIT VERSION
    Function ReverseElements(s As String) As String
        ' In .NET, a text element is series of code units that is displayed as one character, and so reversing the text
        ' elements of the string correctly handles combining character sequences and surrogate pairs.
        Dim elements = Globalization.StringInfo.GetTextElementEnumerator(s)
        Return String.Concat(AsEnumerable(elements).OfType(Of String).Reverse())
    End Function

    ' Wraps an IEnumerator, allowing it to be used as an IEnumerable.
    Iterator Function AsEnumerable(enumerator As IEnumerator) As IEnumerable
        Do While enumerator.MoveNext()
            Yield enumerator.Current
        Loop
    End Function

    Sub Main()
        Const INDENT = "    "

#If REDIRECTOUT Then
        Const OUTPATH = "out.txt"
        Using s = IO.File.Open(OUTPATH, IO.FileMode.Create),
              sw As New IO.StreamWriter(s)
            Console.SetOut(sw)
#Else
        Try
            Console.OutputEncoding = Text.Encoding.ASCII
            Console.OutputEncoding = Text.Encoding.UTF8
            Console.OutputEncoding = Text.Encoding.Unicode
        Catch ex As Exception
            Console.WriteLine("Failed to set console encoding to Unicode." & vbLf)
        End Try
#End If
            For Each c In TestCases
                Console.WriteLine(c)
                Console.WriteLine(INDENT & "SIMPLE:   " & Reverse(c))
                Console.WriteLine(INDENT & "ELEMENTS: " & ReverseElements(c))
                Console.WriteLine()
            Next
#If REDIRECTOUT Then
        End Using
#End If
    End Sub
End Module


x = StringBuilder.new

5.times do
    x.append "ha"
end

puts x # ==> "hahahahaha"


import "/str" for Str
import "/upc" for Graphemes

for (word in ["asdf", "josé", "møøse", "was it a car or a cat I saw", "😀🚂🦊"]) {
    System.print(Str.reverse(word))
}

for (word in ["as⃝df̅", "ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧 👨👩👧👦🆗🗺"]) {
    System.print(Graphemes.new(word).toList[-1..0].join())
}


; the @rev operator reverses strings and arrays
@rev "abc" ; returns "cba"
; or the same thing using a pointer expression
!~r "abc"


RPTSTR(S,N)
 ;Repeat a string S for N times
 NEW I
 FOR I=1:1:N WRITE S
 KILL I
 QUIT
RPTSTR1(S,N) ;Functionally equivalent, but denser to read
 F I=1:1:N W S
 Q


/* Repeat a string, in Neko */
var srep = function(s, n) {
    var str = ""
    while n > 0 {
        str += s
        n -= 1
    }
    return str
}

$print(srep("ha", 5), "\n")


using System;
using System.Console;

module StrRep
{
    Repeat(this s : string, n : int) : string
    {
        String('x', n).Replace("x", s)
    }

    Main() : void
    {
        WriteLine("ha".Repeat(5));
        WriteLine("*".Repeat(5));
        WriteLine(String('*', 5)); // repeating single char

    }
}


include c:\cxpl\codes;  \intrinsic 'code' declarations
string 0;               \use zero-terminated strings, instead of MSb terminated

func StrLen(Str);       \Return the number of characters in an ASCIIZ string
char Str;
int  I;
for I:= 0 to -1>>1-1 do
        if Str(I) = 0 then return I;

func RevStr(S);         \Reverse the order of the bytes in a string
char S;
int  L, I, T;
[L:= StrLen(S);
for I:= 0 to L/2-1 do
        [T:= S(I);  S(I):= S(L-I-1);  S(L-I-1):= T];
return S;
];

[Text(0, RevStr("a")); CrLf(0);
 Text(0, RevStr("ab")); CrLf(0);
 Text(0, RevStr("abc")); CrLf(0);
 Text(0, RevStr("Able was I ere I saw Elba.")); CrLf(0);
]


import strutils

# Repeat a char.
echo repeat('a', 5)     # -> "aaaaa".

# Repeat a string.
echo repeat("ha", 5)    # -> "hahahahaha".


bundle Default {
  class Repeat {
    function : Main(args : String[]) ~ Nil {
      Repeat("ha", 5)->PrintLine();
    }

    function : Repeat(string : String, max : Int) ~ String {
      repeat : String := String->New();
      for(i := 0; i < max; i += 1;) {
        repeat->Append(string);
      };

      return repeat;
    }
  }
}


PrintChar equ $BB5A ;Amstrad CPC bios call
Terminator equ 0    ;null terminator for strings

org $8000
ld hl, StringA
call ReverseString

ld hl, StringA
call PrintString

ret                  ;return to basic

StringA:
byte "12345678",0

;;;; SUBROUTINES
GetStringLength:
;HL = STRING. RETURNS LENGTH IN B. LENGTH IS ONE-INDEXED AND DOES NOT INCLUDE TERMINATOR.
		ld b,0                    ;clear B
loop_getStringLength:
		ld a,(hl)                 ;read the next char
		cp Terminator             ;is it the terminator?
		ret z                     ;if so, exit
		inc hl                    ;point HL to next character
		inc b                     ;increase tally
		jr loop_getStringLength   ;repeat

ReverseString:
	;reverse the order of letters in a text string.
	;e.g. "ABCD" -> "DCBA"
	;the terminator stays put.
	;INPUT: HL = SOURCE ADDRESS OF STRING
	push de
		push hl
			push hl
		             call GetStringLength
			pop hl
		pop de		            ;LD DE,HL
		LD a,b                      ;LOAD B INTO A
		LD (SMC_ReverseString+1),a  ;STORE IT LATER IN THE CODE SO WE CAN RETRIEVE IT.

; TO RECAP, BOTH HL AND DE POINT TO THE BEGINNING OF THE STRING WE WANT TO REVERSE. B EQUALS THE LENGTH OF THE STRING.
; B HAS BEEN BACKED UP WITHOUT USING THE STACK BY STORING IT AS THE OPERAND OF A LATER INSTRUCTION THAT LOADS B WITH A NUMERIC VALUE.
; PUSH BC WOULD NOT HAVE WORKED SINCE THE PROGRAM NEEDS TO PUSH EACH LETTER OF THE STRING DURING THE LOOP.

LOOP_REVERSESTRING_PUSH:
;start at the beginning of the string and push each letter in it, except the terminator.
		ld a,(de)
		push af
		inc de
		djnz LOOP_REVERSESTRING_PUSH

SMC_ReverseString:
		ld b,$42	;LETS US PRESERVE B WITHOUT PUSHING IT. THE $42 IS OVERWRITTEN WITH THE STRING'S LENGTH.

LOOP_REVERSESTRING_POP:
;Starting at the beginning of the string, pop A off the stack and store it into the string. This puts the letters back in the reverse
;   order.
		pop af
		ld (hl),a
		inc hl
		djnz LOOP_REVERSESTRING_POP
	pop de
	ret


@interface NSString (RosettaCodeAddition)
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times;
@end

@implementation NSString (RosettaCodeAddition)
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times {
    return [@"" stringByPaddingToLength:[self length]*times withString:self startingAtIndex:0];
}
@end


let string_repeat s n =
  let s = Bytes.of_string s in
  let len = Bytes.length s in
  let res = Bytes.create (n * len) in
  for i = 0 to pred n do
    Bytes.blit s 0 res (i * len) len
  done;
  (Bytes.to_string res)
;;


program: reverse_string
  input: xyzzy
  output: yzzyx


var s = "socat".*;
std.mem.reverse(u8, &s);


MESSAGE FILL( "ha", 5 ) VIEW-AS ALERT-BOX.


'REPEATING A CHARACTER

print string 10,"A" 'result AAAAAAAAAA

'REPEATING A STRING

function RepeatString(string s,sys n) as string
  sys i, le=len s
  if le=0 then exit function
  n*=le
  function=nuls n
  '
  for i=1 to n step le
    mid function,i,s
  next
end function

print RepeatString "ABC",3 'result ABCABCABC


declare
  fun {Repeat Xs N}
     if N > 0 then
        {Append Xs {Repeat Xs N-1}}
     else
        nil
     end
  end
in
  {System.showInfo {Repeat "Ha" 5}}


repeat(s,n)={
  if(n, Str(repeat(s, n-1), s), "")
};


:start:
V l = File(:argv[1]).read_lines()
l.del(Int(:argv[2]) - 1 .+ Int(:argv[3]))
File(:argv[1], ‘w’).write(l.join("\n"))


def rep  /# s n -- s #/
     "" swap
     for drop
	over chain
     endfor
     nip
enddef

"ha" 5 rep print


with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions;
use Ada.Text_IO;

procedure Remove_Lines_From_File is
   Temporary: constant String := ".tmp";
begin
   if Ada.Command_Line.Argument_Count /= 3 then
      raise Constraint_Error;
   end if;
   declare
      Filename: String := Ada.Command_Line.Argument(1);
      First: Positive := Integer'Value(Ada.Command_Line.Argument(2));
      Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1;
      Input, Output: File_Type;
      Line_Number: Positive := 1;
   begin
      Open(Input, In_File, Filename); -- open original file for reading
      Create(Output, Out_File, Filename & Temporary); -- write to temp. file
      while not End_Of_File(Input) loop
         declare
            Line: String := Get_Line(Input);
         begin
            if Line_Number < First or else Line_Number > Last then
               Put_Line(Output, Line);
            end if;
         end;
         Line_Number := Line_Number + 1;
      end loop;
      Close(Input);
      Close(Output);
      Ada.Directories.Rename(Old_Name => Filename & Temporary,
                             New_Name => Filename);
   end;
exception
   when Constraint_Error | Ada.IO_Exceptions.Name_Error =>
      Put_Line("usage: " & Ada.Command_Line.Command_Name &
                 " <filename> <first> <length>");
      Put_Line("  opens <filename> for reading and " &
                 "<filename>" & Temporary & " for temporary writing");
      Put_Line("  requires first > 0, length >= 0");
end Remove_Lines_From_File;


# removes the specified number of lines from a file, starting at start line (numbered from 1) #
# returns TRUE if successful, FALSE otherwise #
PROC remove lines = ( STRING file name, INT start line, INT number of lines )BOOL:
     IF  number of lines < 0 OR start line < 1
     THEN
        # invalid parameters #
        print( ( "number of lines must be >= 0 and start line must be >= 1", newline ) );
        FALSE
     ELIF  FILE temp file;
           create( temp file, stand back channel ) /= 0
     THEN
        # unable to create a temporary output file #
        print( (  "Unable to create temporary file", newline ) );
        FALSE
     ELIF NOT reset possible( temp file )
     THEN
        # rewinding the temporary file is not possible #
        # we would have to get its name ( with "idf( temp file )", close it and re-open it #
        print( ( "Temp file is not rewindable", newline ) );
        FALSE
     ELIF  FILE input file;
           open( input file, file name, stand in channel ) /= 0
     THEN
        # failed to open the file #
        print( (  "Unable to open """ + file name + """", newline ) );
        FALSE
     ELSE
        # files opened OK #
        BOOL at eof := FALSE;
        # set the EOF handler for the original file #
        on logical file end( input file
                           , ( REF FILE f )BOOL:
                             BEGIN
                                 # note that we reached EOF on the latest read #
                                 at eof := TRUE;
                                 # return TRUE so processing can continue #
                                 TRUE
                             END
                           );
        # copy the input file to the temp file #
        WHILE STRING line;
              get( input file, ( line, newline ) );
              NOT at eof
        DO
            put( temp file,    ( line, newline ) )
        OD;
        # copy the temp file back to the input, removing the specified lines #
        close( input file );
        IF   open( input file, file name, stand out channel ) /= 0
        THEN
            # failed to open the original file for output #
            print( ( "Unable to open ", file name, " for output", newline ) );
            FALSE
        ELSE
            # opened OK - copy the temporary file #
            reset( temp file ); # rewinds the input file #
            at eof := FALSE;
            on logical file end( temp file
                               , ( REF FILE f )BOOL:
                                 BEGIN
                                     # note that we reached EOF on the latest read #
                                     at eof := TRUE;
                                     # return TRUE so processing can continue #
                                     TRUE
                                 END
                               );
            INT end line = ( start line - 1 ) + number of lines;
            INT line number := 0;
            WHILE STRING line;
                  get( temp file, ( line, newline ) );
                  NOT at eof
            DO
                # have another line #
                line number +:= 1;
                IF line number < start line OR line number > end line
                THEN
                    put( input file, ( line, newline ) )
                FI
            OD;
            # close the files #
            close(   input file );
            scratch( temp file  );
            IF   line number < start line
            THEN
                # didn't find the start line #
                print( ( "Specified start line (", whole( start line, 0 ), ") not in ", file name, newline ) );
                FALSE
            ELIF line number < end line
            THEN
                # the ending line was not in the file #
                print( ( "Final omitted line not in the file ", file name, newline ) );
                FALSE
            ELSE
                # successful operation #
                TRUE
            FI
        FI
     FI # remove lines # ;

# test the line removal #
BEGIN
    FILE t;
    open( t, "test.txt", stand out channel );
    print( ( "Before...", newline ) );
    FOR i TO 10 DO
        STRING line = whole( i, - ( ( i MOD 5 ) + 3 ) );
        put( t, ( line, newline ) );
        print(  ( line, newline ) )
    OD;
    close( t );
    remove lines( "test.txt", 2, 3 );
    print( ( "After...", newline ) );
    open( t, "test.txt", stand in channel );
    FOR i TO  7 DO
        STRING line;
        get( t, ( line, newline ) );
        print(  ( line, newline ) )
    OD;
    close( t );
    print( ( "----", newline ) )
END


/* To repeat a string a variable number of times: */

s = repeat('ha', 4);

  /* or */

s = copy('ha', 5);

/* To repeat a single character a fixed number of times: */

s = (5)'h';     /* asigns 'hhhhh' to s. */


#include <hopper.h>

main:
   .ctrlc
   fd=0,fw=0
   fopen(OPEN_READ,"archivo.txt")(fd)
   if file error?
      {"no pude abrir el archivo de lectura: "}
      jsub(show error)
   else
      fcreate(CREATE_NORMAL,"archivoTmp.txt")(fw)
      if file error?
          {"no pude crear el archivo para escritura: "}
          jsub(show error)
      else
          get arg number(2,desde),  // from line
          get arg number(3,hasta),  // to line

          line read=0
          while( not(feof(fd)))
             fread line(1000)(fd), ++line read
             if(not( {line read} between(desde, hasta)))
                 {"\n"}cat,writeline(fw)
             endif
          wend
      endif
   endif
   fclose(fw)
   fclose(fd)
   system("mv archivoTmp.txt archivo.txt")
exit(0)
.locals
show error:
  file error, println
back


RemoveLines(filename, startingLine, numOfLines){
       Loop, Read, %filename%
               if ( A_Index < StartingLine )
                       || ( A_Index >= StartingLine + numOfLines )
                               ret .= "`r`n" . A_LoopReadLine
       FileDelete, % FileName
       FileAppend, % SubStr(ret, 3), % FileName
}

SetWorkingDir, % A_ScriptDir
RemoveLines("test.txt", 4, 3)


# syntax: GAWK -f REMOVE_LINES_FROM_A_FILE.AWK
# show files after lines are removed:
#   GAWK "FNR==1{print(FILENAME)};{print(FNR,$0)}" TEST1 TEST2 TEST3
BEGIN {
    build_test_data()
    remove_lines("TEST0",1,1)
    remove_lines("TEST1",3,4)
    remove_lines("TEST2",9,3)
    remove_lines("TEST3",11,1)
    exit(errors+0)
}
function build_test_data(  fn,i,j) { # create 3 files with 10 lines each
    for (i=1; i<=3; i++) {
      fn = "TEST" i
      for (j=1; j<=10; j++) {
        printf("line %d\n",j) >fn
      }
      close(fn)
    }
}
function remove_lines(fn,start,number_of_lines,  arr,fnr,i,n,rec,stop) {
    stop = start + number_of_lines - 1
    while (getline rec <fn > 0) { # read file
      fnr++
      if (fnr < start || fnr > stop) {
        arr[++n] = rec
      }
    }
    close(fn)
    if (fnr == 0) {
      printf("error: file %s not found\n",fn)
      errors = 1
      return
    }
    for (i=1; i<=n; i++) { # write file
      printf("%s\n",arr[i]) >fn
    }
    close(fn)
    if (stop > fnr) {
      printf("error: file %s trying to remove nonexistent lines\n",fn)
      errors = 1
    }
}


To run:
Start up.
Put "ha" into a string.
Append the string to itself given 5.
Write the string on the console.
Fill another string with the asterisk byte given 5.
Write the other string on the console.
Wait for the escape key.
Shut down.

To append a string to itself given a number:
If the number is less than 1, exit.
Privatize the string.
Privatize the number.
Subtract 1 from the number.
Append the string to the original string given the number.


% the comments show the stack content after the line was executed
% where rcount is the repeat count, "o" is for orignal,
% "f" is for final, and iter is the for loop variable
%
% usage: rcount ostring times -> fstring

/times {
  dup length dup    % rcount ostring olength olength
  4 3 roll          % ostring olength olength rcount
  mul dup string    % ostring olength flength fstring
  4 1 roll          % fstring ostring olength flength
  1 sub 0 3 1 roll  % fstring ostring 0 olength flength_minus_one
  {                 % fstring ostring iter
    1 index 3 index % fstring ostring iter ostring fstring
    3 1 roll        % fstring ostring fstring iter ostring
    putinterval     % fstring ostring
  } for
  pop               % fstring
} def


' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' Remove File Lines V1.1                            '
'                                                   '
' Developed by A. David Garza Marín in VB-DOS for   '
' RosettaCode. November 30, 2016.                   '
'                                                   '
' Date      | Change                                '
'-------------------------------------------------- '
' 2016/11/30| Original version                      '
' 2016/12/30| Added functionality to read parameters'
'           | from Command Line                     '
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '

'OPTION _EXPLICIT ' For QB45
OPTION EXPLICIT ' For VBDOS, PDS 7.1

' SUBs and FUNCTIONs
DECLARE FUNCTION DeleteLinesFromFile% (WhichFile AS STRING, Start AS LONG, HowMany AS LONG)
DECLARE FUNCTION FileExists% (WhichFile AS STRING)
DECLARE FUNCTION GetDummyFile$ (WhichFile AS STRING)
DECLARE FUNCTION getFileName$ (CommandString AS STRING)
DECLARE FUNCTION getHowManyLines& (CommandLine AS STRING)
DECLARE FUNCTION getStartPoint& (CommandLine AS STRING)
DECLARE FUNCTION ErrorMessage$ (WhichError AS INTEGER)
DECLARE FUNCTION CountLines& (WhichFile AS STRING)

' Var
DIM iOk AS INTEGER, iErr AS INTEGER, lStart AS LONG, lHowMany AS LONG, lSize AS LONG
DIM sFile AS STRING, sCommand AS STRING

' Const
CONST ProgramName = "RemFLine (Remove File Lines) Enhanced V1.1"

' ----------------------------- Main program cycle --------------------------------
CLS
PRINT ProgramName
PRINT
PRINT "This program will remove as many lines of a text file as you state, starting"
PRINT "with the line number you also state. If the starting line number is beyond"
PRINT "total lines in the text file stated, then the process will be aborted. If the"
PRINT "quantity of lines stated to be deleted is beyond the total lines in the text"
PRINT "file, the process also will be aborted. The program will give you a message"
PRINT "if everything ran ok or if any error happened. Includes a function to count"
PRINT "how many lines has the intended file."
' Verifies if parameters are specified
sCommand = COMMAND$
IF sCommand <> "" THEN
  sFile = getFileName$(sCommand)
  lSize = CountLines&(sFile)
  lStart = getStartPoint&(sCommand)  ' Defaults to 1
  lHowMany = getHowManyLines&(sCommand) ' Defaults to 1
ELSE
  PRINT
  INPUT "Please, type the name of the file"; sFile
  sFile = LTRIM$(RTRIM$(sFile))
  IF sFile <> "" THEN
    lSize = CountLines&(sFile)
    IF lSize > 0 THEN
      PRINT "Delete starting on which line (Default=1, Max="; lSize; ")";
      INPUT lStart

      IF lStart = 0 THEN lStart = 1
      IF lStart < lSize THEN
        PRINT "How many lines do you want to remove (Default=1, Max="; (lSize - lStart) + 1; ")";
        INPUT lHowMany
        IF lHowMany = 0 THEN lHowMany = 1
      END IF
    END IF
  END IF
END IF

PRINT
PRINT "Erasing "; lHowMany; "lines from "; sFile; " starting on line"; lStart; "."
IF lSize > 0 THEN
  IF lHowMany + lStart <= lSize THEN
    iOk = DeleteLinesFromFile%(sFile, lStart, lHowMany)
  ELSEIF lHowMany + lStart > lSize THEN
    iOk = 1
  ELSEIF lStart > lSize THEN
    iOk = 2
  END IF
ELSEIF lSize = -1 THEN
  iOk = 3
END IF

IF lSize = -1 THEN
  iOk = 3
ELSEIF lSize = 0 THEN
  iOk = 4  ' The file is not a text file
END IF

IF sFile = "" THEN
  iOk = 5  ' Null file name not allowed
END IF

PRINT
PRINT ErrorMessage$(iOk)
'----------------End of Main program Cycle ----------------

END

FileError:
    iErr = ERR
RESUME NEXT

FUNCTION CountLines& (WhichFile AS STRING)
    ' Var
    DIM iFile AS INTEGER
    DIM l AS LONG, li AS LONG, j AS LONG, lFileSize AS LONG, lLines AS LONG
    DIM sLine AS STRING, strR AS STRING

    ' This function will count how many lines has the file
    IF FileExists%(WhichFile) THEN
        strR = CHR$(13)
        li = 1
        iFile = FREEFILE
        sLine = SPACE$(128)
        lLines = 0
        OPEN WhichFile FOR BINARY AS #iFile
          lFileSize = LOF(iFile)
          DO
            IF (LOC(iFile) + LEN(sLine)) > lFileSize THEN
              sLine = SPACE$(lFileSize - LOC(iFile))
            END IF
            IF LEN(sLine) > 0 THEN
              GET #iFile, , sLine
              GOSUB AnalizeLine
            END IF
          LOOP UNTIL LEN(sLine) < 128
        CLOSE iFile
    ELSE
        lLines = -1
    END IF

    CountLines& = lLines

EXIT FUNCTION

AnalizeLine:
   li = 1
   DO
     l = INSTR(li, sLine, strR)
     IF l > 0 THEN
       lLines = lLines + 1
       li = l + 1
     END IF
   LOOP UNTIL l = 0
RETURN
END FUNCTION

FUNCTION DeleteLinesFromFile% (WhichFile AS STRING, Start AS LONG, HowMany AS LONG)
    ' Var
    DIM lCount AS LONG, iFile AS INTEGER, iFile2 AS INTEGER, lhm AS LONG, iError AS INTEGER
    DIM sLine AS STRING, sDummyFile AS STRING

    IF FileExists%(WhichFile) THEN
        sDummyFile = GetDummyFile$(WhichFile)

        ' It is assumed a text file
        iFile = FREEFILE
        OPEN WhichFile FOR INPUT AS #iFile

        iFile2 = FREEFILE
        OPEN sDummyFile FOR OUTPUT AS #iFile2

        lhm = 0
        DO WHILE NOT EOF(iFile)
            LINE INPUT #iFile, sLine
            lCount = lCount + 1
            IF lCount >= Start AND lhm < HowMany THEN
                lhm = lhm + 1
            ELSE
                PRINT #iFile2, sLine
            END IF
        LOOP

        CLOSE iFile2, iFile

        ' Check if everything went ok or not
        iError = 0
        IF lCount < Start THEN
            iError = 2 ' Full file is shorter than the start line stated,
                       '  process will be aborted.
        ELSEIF lhm < HowMany THEN
            iError = 1 ' File was shorter than lines requested to be removed,
                       '  process will be aborted.
        END IF

        IF iError > 0 THEN
          KILL sDummyFile  ' Process aborted
        ELSE
          KILL WhichFile
          NAME sDummyFile AS WhichFile
        END IF
    ELSE
      iError = 3 ' The file doesn't exist. The process is aborted.
    END IF

    DeleteLinesFromFile% = iError

END FUNCTION

FUNCTION ErrorMessage$ (WhichError AS INTEGER)
    ' Var
    DIM sError AS STRING

    SELECT CASE WhichError
      CASE 0: sError = "Everything went Ok. Lines removed from file."
      CASE 1: sError = "File is shorter than the number of lines stated to remove. Process aborted."
      CASE 2: sError = "Whole file is shorter than the starting point stated. Process aborted."
      CASE 3: sError = "File doesn't exist. Process aborted."
      CASE 4: sError = "The file doesn't seem to be a text file. Process aborted."
      CASE 5: sError = "You need to provide a valid file name, please."
    END SELECT

    ErrorMessage$ = sError
END FUNCTION

FUNCTION FileExists% (WhichFile AS STRING)
    ' Var
    DIM iFile AS INTEGER
    DIM iItExists AS INTEGER
    SHARED iErr AS INTEGER

    ON ERROR GOTO FileError
    iFile = FREEFILE
    iErr = 0
    OPEN WhichFile FOR BINARY AS #iFile
    IF iErr = 0 THEN
        iItExists = LOF(iFile) > 0
        CLOSE #iFile

        IF NOT iItExists THEN
            KILL WhichFile
        END IF
    END IF
    ON ERROR GOTO 0
    FileExists% = iItExists

END FUNCTION

FUNCTION GetDummyFile$ (WhichFile AS STRING)
    ' Var
    DIM i AS INTEGER, j AS INTEGER

    ' Gets the path specified in WhichFile
    i = 1
    DO
        j = INSTR(i, WhichFile, "\")
        IF j > 0 THEN i = j + 1
    LOOP UNTIL j = 0

    GetDummyFile$ = LEFT$(WhichFile, i - 1) + "$dummyf$.tmp"
END FUNCTION

FUNCTION getFileName$ (CommandString AS STRING)
  ' Var
  DIM i AS INTEGER
  DIM sFileName AS STRING

  i = INSTR(CommandString, ",")
  IF i > 0 THEN
    sFileName = LEFT$(CommandString, i - 1)
  ELSEIF LEN(CommandString) > 0 THEN
    sFileName = CommandString
  END IF

  getFileName$ = sFileName
END FUNCTION

FUNCTION getHowManyLines& (CommandLine AS STRING)
  ' Var
  DIM i AS INTEGER, j AS INTEGER
  DIM l AS LONG

  i = INSTR(CommandLine, ",")
  IF i > 0 THEN
    j = INSTR(i + 1, CommandLine, ",")
    IF j = 0 THEN
      l = 1
    ELSE
      l = CLNG(VAL(MID$(CommandLine, j + 1)))
    END IF
  END IF

  getHowManyLines& = l

END FUNCTION

FUNCTION getStartPoint& (CommandLine AS STRING)
  ' Var
  DIM i AS INTEGER, j AS INTEGER
  DIM l AS LONG

  i = INSTR(CommandLine, ",")
  IF i > 0 THEN
    j = INSTR(i + 1, CommandLine, ",")
    IF j = 0 THEN j = LEN(CommandLine)
    l = CLNG(VAL(MID$(CommandLine, i + 1, j - i)))
  ELSE
    i = 1
  END IF

  getStartPoint& = l

END FUNCTION


void setup() {
  String rep = repeat("ha", 5);
  println(rep);
}
String repeat(String str, int times) {
  // make an array of n chars,
  // replace each char with str,
  // and return as a new String
  return new String(new char[times]).replace("\0", str);
}


%repeat(Str,Num,Res).
repeat(Str,1,Str).
repeat(Str,Num,Res):-
    Num1 is Num-1,
    repeat(Str,Num1,Res1),
    string_concat(Str, Res1, Res).


> str_repeat 0 s = "";
> str_repeat n s = s + (str_repeat (n-1) s) if n>0;
> str_repeat 5 "ha";
"hahahahaha"
>


#include <stdio.h>
#include <stdlib.h> /* for atoi() and malloc() */
#include <string.h> /* for memmove() */

/* Conveniently print to standard error and exit nonzero. */
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)

int main(int argc, char **argv)
{
    FILE *fp;
    char *buf;
    size_t sz;
    int start, count, lines = 1;
    int dest = 0, src = 0, pos = -1;

    /* Initialization and sanity checks */
    if (argc != 4)
        ERROR("Usage: %s <file> <start> <count>", argv[0]);

    if ((count = atoi(argv[3])) < 1) /* We're a no-op. */
        return 0;

    if ((start = atoi(argv[2])) < 1)
        ERROR("Error: <start> (%d) must be positive", start);

    if ((fp = fopen(argv[1], "r")) == NULL)
        ERROR("No such file: %s", argv[1]);

    /* Determine filesize and allocate a buffer accordingly. */
    fseek(fp, 0, SEEK_END);
    sz = ftell(fp);
    buf = malloc(sz + 1);
    rewind(fp);

    /* Fill the buffer, count lines, and remember a few important offsets. */
    while ((buf[++pos] = fgetc(fp)) != EOF) {
        if (buf[pos] == '\n') {
            ++lines;
            if (lines == start) dest = pos + 1;
            if (lines == start + count) src = pos + 1;
        }
    }

    /* We've been asked to do something weird; clean up and bail. */
    if (start + count > lines) {
        free(buf);
        fclose(fp);
        ERROR("Error: invalid parameters for file with %d lines", --lines);
    }

    /* Overwrite the lines to be deleted with the survivors. */
    memmove(buf + dest, buf + src, pos - src);

    /* Reopen the file and write back just enough of the buffer. */
    freopen(argv[1], "w", fp);
    fwrite(buf, pos - src + dest, 1, fp);

    free(buf);
    fclose(fp);
    return 0;
}


Procedure.s RepeatString(count, text$=" ")
   Protected i, ret$=""

   For i = 1 To count
      ret$ + text$
   Next
   ProcedureReturn ret$
EndProcedure

Debug RepeatString(5, "ha")


using System;
using System.IO;
using System.Linq;

public class Rosetta
{
    public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);

    static void RemoveLines(string filename, int start, int count = 1) =>
        File.WriteAllLines(filename, File.ReadAllLines(filename)
            .Where((line, index) => index < start - 1 || index >= start + count - 1));
}


#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>

void deleteLines( const std::string & , int , int ) ;

int main( int argc, char * argv[ ] ) {
   if ( argc != 4 ) {
      std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
      return 1 ;
   }
   std::string filename( argv[ 1 ] ) ;
   int startfrom = atoi( argv[ 2 ] ) ;
   int howmany = atoi( argv[ 3 ] ) ;
   deleteLines ( filename , startfrom , howmany ) ;
   return 0 ;
}

void deleteLines( const std::string & filename , int start , int skip ) {
   std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
   if ( infile.is_open( ) ) {
      std::string line ;
      std::list<std::string> filelines ;
      while ( infile ) {
	 getline( infile , line ) ;
	 filelines.push_back( line ) ;
      }
      infile.close( ) ;
      if ( start > filelines.size( ) ) {
	 std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
	 return ;
      }
      if ( ( start + skip ) > filelines.size( ) ) {
	 std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
	 return ;
      }
      std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
      for ( int i = 1 ; i < start ; i++ )
	 deletebegin++ ;
      deleteend = deletebegin ;
      for( int i = 0 ; i < skip ; i++ )
	 deleteend++ ;
      filelines.erase( deletebegin , deleteend ) ;
      std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
      if ( outfile.is_open( ) ) {
	 for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
	       sli != filelines.end( ) ; sli++ )
	    outfile << *sli << "\n" ;
      }
      outfile.close( ) ;
   }
   else {
      std::cerr << "Error! Could not find file " << filename << " !\n" ;
      return ;
   }
}


#lang racket
;; fast
(define (string-repeat n str)
  (string-append* (make-list n str)))
(string-repeat 5 "ha") ; => "hahahahaha"


'For a single char
showmessage String$(10, "-")

'For strings with more than one char
function Repeat$(Expr as string, Count as integer) as string
    dim x as integer
    for x = 1 to Count
        Result = Result + Expr
    next
end function

showmessage Repeat$("ha", 5)


Function Repeat(s As String, count As Integer) As String
  Dim output As String
  For i As Integer = 0 To count
    output = output + s
  Next
  Return output
End Function


using System;
using System.Reflection;

public class Rosetta
{
    public static void Main()
    {
        //Let's get all methods, not just public ones.
        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static
            | BindingFlags.Public | BindingFlags.NonPublic
            | BindingFlags.DeclaredOnly;

        foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))
            Console.WriteLine(method);
    }

    class TestForMethodReflection
    {
        public void MyPublicMethod() {}
        private void MyPrivateMethod() {}

        public static void MyPublicStaticMethod() {}
        private static void MyPrivateStaticMethod() {}
    }

}


(require '[clojure.java.io :as jio]
         '[clojure.string :as str])

(defn remove-lines1 [filepath start nskip]
  (let [lines (str/split-lines (slurp filepath))
        new-lines (concat (take (dec start) lines)
                          (drop (+ (dec start) nskip) lines))
        diff (- (count lines) (count new-lines))]
    (when-not (zero? diff)
      (println "WARN: You are trying to remove lines beyond EOF"))
    (with-open [wrt (jio/writer (str filepath ".tmp"))]
      (.write wrt (str/join "\n" new-lines)))
    (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))


>> str: "Add duplicates to string"
>> insert/dup str "ha" 3
== "hahahaAdd duplicates to string"
>> insert/dup tail str "ha" 3
== "hahahaAdd duplicates to stringhahaha"


with strings'
: repeatString ( $n-$ )
  1- [ dup ] dip [ over prepend ] times nip ;

"ha" 5 repeatString


; Including listing private methods in the clojure.set namespace:
=> (keys (ns-interns 'clojure.set))
(union map-invert join select intersection superset? index bubble-max-key subset? rename rename-keys project difference)

; Only public:
=> (keys (ns-publics 'clojure.set))
(union map-invert join select intersection superset? index subset? rename rename-keys project difference)


struct S {
    bool b;

    void foo() {}
    private void bar() {}
}

class C {
    bool b;

    void foo() {}
    private void bar() {}
}

void printMethods(T)() if (is(T == class) || is(T == struct)) {
    import std.stdio;
    import std.traits;

    writeln("Methods of ", T.stringof, ":");
    foreach (m; __traits(allMembers, T)) {
        static if (__traits(compiles, (typeof(__traits(getMember, T, m))))) {
            alias typeof(__traits(getMember, T, m)) ti;
            static if (isFunction!ti) {
                writeln("    ", m);
            }
        }
    }
}

void main() {
    printMethods!S;
    printMethods!C;
}


import system'routines;
import system'dynamic;
import extensions;

class MyClass
{
    myMethod1() {}

    myMethod2(x) {}
}

public program()
{
    var o := new MyClass();

    o.__getClass().__getMessages().forEach:(p)
    {
        console.printLine("o.",p)
    }
}


USING: io math prettyprint see ;

"The list of methods contained in the generic word + :" print
\ + methods . nl

"The list of methods specializing on the fixnum class:" print
fixnum methods .


(defun remove-lines (filename start num)
  (let ((tmp-filename  (concatenate 'string filename ".tmp"))
	(lines-omitted 0))
    ;; Open a temp file to write the result to
    (with-open-file (out tmp-filename
			 :direction :output
			 :if-exists :supersede
			 :if-does-not-exist :create)
      ;; Open the original file for reading
      (with-open-file (in filename)
	(loop
	   for line = (read-line in nil 'eof)
	   for i from 1
	   until (eql line 'eof)
	   ;; Write the line to temp file if it is not in the omitted range
	   do (if (or (< i start)
		      (>= i (+ start num)))
		(write-line line out)
		(setf lines-omitted (1+ lines-omitted))))))
    ;; Swap in the temp file for the original
    (delete-file filename)
    (rename-file tmp-filename filename)
    ;; Warn if line removal went past the end of the file
    (when (< lines-omitted num)
      (warn "End of file reached with only ~d lines removed." lines-omitted))))


import std.stdio, std.file, std.string;

void main() {
    deleteLines("deleteline_test.txt", 1, 2);
}

void deleteLines(string name, int start, int num)
in {
    assert(start > 0, "Line counting must start at 1");
} body {
    start--;

    if (!exists(name) || !isFile(name))
        throw new FileException("File not found");

    auto lines = readText(name).splitLines();
    if (lines.length < start + num)
        throw new Exception("Can't delete lines past the end of file!");

    auto f = File(name, "w");
    foreach (int i, line; lines) {
        if (start > i || i >= start + num)
            f.writeln(line);
    }
}


/*REXX program to show various ways to repeat a string (or repeat a single char).*/

/*all examples are equivalent, but not created equal.*/

                           /*───────────────────────────────────────────*/
y='ha'
z=copies(y,5)
                           /*───────────────────────────────────────────*/
z=copies( 'ha', 5 )
                           /*───────────────────────────────────────────*/
y='ha'
z=y||y||y||y||y
                           /*───────────────────────────────────────────*/
y='ha'
z=y || y || y || y || y    /*same as previous, but the "big sky" version*/
                           /*───────────────────────────────────────────*/
y='ha'
z=''
       do 5
       z=z||y
       end
                           /*───────────────────────────────────────────*/
y="ha"
z=
       do 5
       z=z||y
       end
                           /*───────────────────────────────────────────*/
y="ha"
z=
       do i=101 to 105
       z=z||y
       end

                           /*───────────────────────────────────────────*/
y='+'
z=left('',5,y)
                           /*───────────────────────────────────────────*/
y='+'
z=right('',5,y)
                           /*───────────────────────────────────────────*/
y='+'
z=substr('',1,5,y)
                           /*───────────────────────────────────────────*/
y='+'
z=center('',5,y)
                           /*───────────────────────────────────────────*/
y='+'
z=centre('',5,y)
                           /*───────────────────────────────────────────*/
y='+'
z=space('',5,y)
                           /*───────────────────────────────────────────*/
y='+'
z=translate('@@@@@',y,"@")
                           /*───────────────────────────────────────────*/
y='abcdef'
z=five(y)
exit

five: procedure expose y; parse arg g
if length(g)>=5*length(y) then return g
return five(y||g)
                           /*───────────────────────────────────────────*/
y='something wicked this way comes.'
z=y||y||y||y||y||y||y||y||y||y||y||y|\y||y||y
z=left(z,5*length(y))
                           /*───────────────────────────────────────────*/
y='+'
z=copies('',5,y)
                           /*───────────────────────────────────────────*/
y='+'
z=lower('',1,5,y)
                           /*───────────────────────────────────────────*/
y='+'
z=lower('',,5,y)
                           /*───────────────────────────────────────────*/
z='+'
z=upper('',1,5,y)
                           /*───────────────────────────────────────────*/
z=upper('',,5,y)
                           /*───────────────────────────────────────────*/

y='charter bus.'
z='*****'
z=changestr('*',z,y)
                           /*───────────────────────────────────────────*/
y='what the hey!'
z=
  do until length(z)==5*length(y)
  z=z||y
  end
                           /*───────────────────────────────────────────*/
y='what the hey!'
z=
  do until length(z)==5*length(y)
  z=insert(z,0,y)
  end
                           /*───────────────────────────────────────────*/
y='yippie ki yay'
z=
   do i=1 by 5 for 5
   z=overlay(y,z,i)
   end
                           /*───────────────────────────────────────────*/
y='+'
z=justify('',5,y)
                           /*───────────────────────────────────────────*/
whatever_this_variable_is_____it_aint_referenced_directly= 'boy oh boy.'
z=; signal me; me:
  do 5
  z=z||strip(subword(sourceline(sigl-1),2),,"'")
  end
                           /*───────────────────────────────────────────*/
y="any more examples & the angry townfolk with pitchforks will burn the castle."
parse value y||y||y||y||y with z

exit                                   /*stick a fork in it, we're done.*/


package main

import (
	"fmt"
	"image"
	"reflect"
)

type t int // A type definition

// Some methods on the type
func (r t) Twice() t       { return r * 2 }
func (r t) Half() t        { return r / 2 }
func (r t) Less(r2 t) bool { return r < r2 }
func (r t) privateMethod() {}

func main() {
	report(t(0))
	report(image.Point{})
}

func report(x interface{}) {
	v := reflect.ValueOf(x)
	t := reflect.TypeOf(x) // or v.Type()
	n := t.NumMethod()
	fmt.Printf("Type %v has %d exported methods:\n", t, n)
	const format = "%-6s %-46s %s\n"
	fmt.Printf(format, "Name", "Method expression", "Method value")
	for i := 0; i < n; i++ {
		fmt.Printf(format,
			t.Method(i).Name,
			t.Method(i).Func.Type(),
			v.Method(i).Type(),
		)
	}
	fmt.Println()
}


   NB. define a stack class
   coclass 'Stack'
   create =: 3 : 'items =: i. 0'
   push =: 3 : '# items =: items , < y'
   top =: 3 : '> {: items'
   pop =: 3 : ([;._2' a =. top 0; items =: }: items; a;')
   destroy =: codestroy
   cocurrent 'base'

   names_Stack_''      NB. all names
create  destroy pop     push    top

   'p' names_Stack_ 3  NB. verbs that start with p
pop  push

   NB. make an object.  The dyadic definition of cownew invokes the create verb
   S =: conew~ 'Stack'

   names__S''          NB. object specific names
COCREATOR items

   pop__S              NB. introspection: get the verbs definition
3 : 0
 a =. top 0
 items =: }: items
 a
)

   NB. get the search path of object S
   copath S
┌─────┬─┐
│Stack│z│
└─────┴─┘

   names__S 0         NB. get the object specific data
COCREATOR items


import java.lang.reflect.Method;

public class ListMethods {
    public int examplePublicInstanceMethod(char c, double d) {
        return 42;
    }

    private boolean examplePrivateInstanceMethod(String s) {
        return true;
    }

    public static void main(String[] args) {
        Class clazz = ListMethods.class;

        System.out.println("All public methods (including inherited):");
        for (Method m : clazz.getMethods()) {
            System.out.println(m);
        }
        System.out.println();
        System.out.println("All declared methods (excluding inherited):");
        for (Method m : clazz.getDeclaredMethods()) {
            System.out.println(m);
        }
    }
}


program Remove_lines_from_a_file_using_TStringDynArray;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.IoUtils;

// zero started Index
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
  if not FileExists(FileName) then
    exit;

  var lines := TFile.ReadAllLines(FileName);

  Delete(lines, Index, Line_count);
  TFile.WriteAllLines(FileName, lines);
end;

begin
  // Remove 2th & 3td line of file
  RemoveLines('input.txt', 1, 2);
end.


IMPORT STD;
RemoveLines(logicalfile, startline, numlines) := FUNCTIONMACRO
  EndLine := startline + numlines - 1;
  RecCnt  := COUNT(logicalfile);
  Res := logicalfile[1..startline-1] + logicalfile[endline+1..];
  RETURN WHEN(IF(RecCnt < EndLine,logicalfile,Res),
              IF(RecCnt < EndLine,STD.System.Log.addWorkunitWarning('Attempted removal past end of file-removal ignored')));
ENDMACRO;


defmodule RC do
  def remove_lines(filename, start, number) do
    File.open!(filename, [:read], fn file ->
      remove_lines(file, start, number, IO.read(file, :line))
    end)
  end

  defp remove_lines(_file, 0, 0, :eof), do: :ok
  defp remove_lines(_file, _, _, :eof) do
    IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
  end
  defp remove_lines(file, 0, 0, line) do
    IO.write line
    remove_lines(file, 0, 0, IO.read(file, :line))
  end
  defp remove_lines(file, 0, number, _line) do
    remove_lines(file, 0, number-1, IO.read(file, :line))
  end
  defp remove_lines(file, start, number, line) do
    IO.write line
    remove_lines(file, start-1, number, IO.read(file, :line))
  end
end

[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)


a$ = "ha "
for i = 1 to 5
  a1$ = a1$ + a$
next i
a$ = a1$
print a$


std::iter::repeat("ha").take(5).collect::<String>(); // ==> "hahahahaha"


// Sample classes for reflection
function Super(name) {
    this.name = name;
    this.superOwn = function() { return 'super owned'; };
}
Super.prototype = {
    constructor: Super
    className: 'super',
    toString: function() { return "Super(" + this.name + ")"; },
    doSup: function() { return 'did super stuff'; }
}

function Sub() {
    Object.getPrototypeOf(this).constructor.apply(this, arguments);
    this.rest = [].slice.call(arguments, 1);
    this.subOwn = function() { return 'sub owned'; };
}
Sub.prototype = Object.assign(
    new Super('prototype'),
    {
        constructor: Sub
        className: 'sub',
        toString: function() { return "Sub(" + this.name + ")"; },
        doSub: function() { return 'did sub stuff'; }
    });

Object.defineProperty(Sub.prototype, 'shush', {
    value: function() { return ' non-enumerable'; },
    enumerable: false // the default
});

var sup = new Super('sup'),
    sub = new Sub('sub', 0, 'I', 'two');

Object.defineProperty(sub, 'quiet', {
    value: function() { return 'sub owned non-enumerable'; },
    enumerable: false
});

// get enumerable methods on an object and its ancestors
function get_method_names(obj) {
    var methods = [];
    for (var p in obj) {
        if (typeof obj[p] == 'function') {
            methods.push(p);
        }
    }
    return methods;
}

get_method_names(sub);
//["subOwn", "superOwn", "toString", "doSub", "doSup"]

// get enumerable properties on an object and its ancestors
function get_property_names(obj) {
    var properties = [];
    for (var p in obj) {
        properties.push(p);
    }
    return properties;
}

// alternate way to get enumerable method names on an object and its ancestors
function get_method_names(obj) {
    return get_property_names(obj)
        .filter(function(p) {return typeof obj[p] == 'function';});
}

get_method_names(sub);
//["subOwn", "superOwn", "toString", "doSub", "doSup"]

// get enumerable & non-enumerable method names set directly on an object
Object.getOwnPropertyNames(sub)
    .filter(function(p) {return typeof sub[p] == 'function';})
//["subOwn", "shhh"]

// get enumerable method names set directly on an object
Object.keys(sub)
    .filter(function(p) {return typeof sub[p] == 'function';})
//["subOwn"]

// get enumerable method names & values set directly on an object
Object.entries(sub)
    .filter(function(p) {return typeof p[1] == 'function';})
//[["subOwn", function () {...}]]


-module( remove_lines ).

-export( [from_file/3, task/0] ).

from_file( Name, Start, How_many ) ->
	{Name, {ok, Binary}} = {Name, file:read_file( Name )},
	Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
	{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
	ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
	io:fwrite( "~s~n", [Message] ).

task() ->
	file:copy( "priv/foobar.txt", "foobar.txt" ),
	from_file( "foobar.txt", 1, 2 ).

compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).

keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
	{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many  > Available ->
	Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
	{Keeps, _Removes} = lists:split( Start, Lines ),
	{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
	{Keeps, Removes} = lists:split( Start, Lines ),
	{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.


(define (string-repeat n str)
  (apply string-append (vector->list (make-vector n str))))


$ echo ha | sed 's/.*/&&&&&/'
hahahahaha


// Version 1.2.31

import kotlin.reflect.full.functions

open class MySuperClass {
    fun mySuperClassMethod(){}
}

open class MyClass : MySuperClass() {
    fun myPublicMethod(){}

    internal fun myInternalMethod(){}

    protected fun myProtectedMethod(){}

    private fun myPrivateMethod(){}
}

fun main(args: Array<String>) {
    val c = MyClass::class
    println("List of methods declared in ${c.simpleName} and its superclasses:\n")
    val fs = c.functions
    for (f in fs) println("${f.name}, ${f.visibility}")
}


-- parent script "MyClass"

on foo (me)
  put "foo"
end

on bar (me)
  put "bar"
end


function helloWorld()
    print "Hello World"
end

-- Will list all functions in the given table, but does not recurse into nexted tables
function printFunctions(t)
    local s={}
    local n=0
    for k in pairs(t) do
        n=n+1 s[n]=k
    end
    table.sort(s)
    for k,v in ipairs(s) do
        f = t[v]
        if type(f) == "function" then
            print(v)
        end
    end
end

printFunctions(_G)


// create a class with methods that will be listed
class Methods
	def static method1()
		return "this is a static method. it will not be printed"
	end
	def method2()
		return "this is not a static method"
	end

	def operator=(other)
		// operator methods are listed by both their defined name and
		// by their internal name, which in this case is isEqual
		return true
	end
end

// lists all nanoquery and java native methods
for method in dir(new(Methods))
	println method
end


type Foo = object
proc bar(f:Foo) = echo "bar"
var f:Foo
f.bar()


open System
open System.IO

let cutOut (arr : 'a[]) from n =  // confine syntax highlighting confusion'
    let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
    ((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)

[<EntryPoint>]
let main argv =
    let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
    let lines = File.ReadAllLines(argv.[0])
    let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
    if tooShort then Console.Error.WriteLine "Not enough lines"
    File.WriteAllLines(argv.[0], sliced)
    0


      SUBROUTINE CROAK(GASP)	!Something bad has happened.
       CHARACTER*(*) GASP	!As noted.
        WRITE (6,*) "Oh dear. ",GASP	!So, gasp away.
        STOP "++ungood."	!Farewell, cruel world.
      END			!No return from this.

      SUBROUTINE FILEHACK(FNAME,IST,N)
       CHARACTER*(*) FNAME	!Name for the file.
       INTEGER IST		!First record to be omitted.
       INTEGER N		!Number of records to be omitted.
       INTEGER ENUFF,L		!Some lengths.
       PARAMETER (ENUFF = 66666)!Surely?
       CHARACTER*(ENUFF) ALINE	!But not in general...
       INTEGER NREC		!A counter.
       INTEGER F,T		!Mnemonics for file unit numbers.
       PARAMETER (F=66,T=67)	!These should do.
       LOGICAL EXIST
        IF (FNAME.EQ."") CALL CROAK("Blank file name!")
        IF (IST.LE.0)    CALL CROAK("First record must be positive!")
        IF (N.LE.0)      CALL CROAK("Remove count must be positive!")
        INQUIRE(FILE = FNAME, EXIST = EXIST)	!This mishap is frequent, so attend to it.
        IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)	!Tough love.
        OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")	!Grab the source file.
        OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")	!Request a temporary file.
        NREC = 0		!Number of records read so far.
Copy the desired records to a temporary file.
   10   READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))	!Minimal protection.
   11   FORMAT (Q,A)		!Obviously, Q = # of characters to come, A = their format.
        IF (L.GT.ENUFF) CALL CROAK("Ow! Lengthy record!!")
        NREC = NREC + 1		!If we're here. we've read a record.
        IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)	!A desired record?
   12   FORMAT (A)		!No character count is explicitly specified.
        GO TO 10		!Keep on thumping.
Convert from input to output...
   20   IF (NREC.LT.IST + N) CALL CROAK("Insufficient records!")	!Finished ignoring records?
        REWIND T		!Not CLOSE! That would discard the file!
        CLOSE(F)		!The source file still exists.
        OPEN (F,FILE=FNAME,FORM="FORMATTED",	!But,
     1   ACTION="WRITE",STATUS="REPLACE")	!This dooms it!
Copy from the temporary file.
   21   READ (T,11,END = 30) L,ALINE(1:L)	!All records are not longer than ALINE.
        WRITE (F,12) ALINE(1:L)			!Out it goes.
        GO TO 21		!Keep on thumping.
Completed.
   30   CLOSE(T)		!Abandon the temporary file.
        CLOSE(F)		!Finished with the source file.
      END		!Done.

      PROGRAM CHOPPER
       CALL FILEHACK("foobar.txt",1,2)
      END


$ include "seed7_05.s7i";

const proc: main is func
  begin
    writeln("ha" mult 5);
  end func;


put "Ho!" repeated 3 times

put "Merry" repeated to length 12


 10 LET S$="HA"
 20 LET N=5
 30 GOSUB 60
 40 PRINT T$
 50 STOP
 60 LET T$=""
 70 FOR I=1 TO N
 80 LET T$=T$+S$
 90 NEXT I
100 RETURN


#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface Foo : NSObject
@end
@implementation Foo
- (int)bar:(double)x {
  return 42;
}
@end

int main() {
  unsigned int methodCount;
  Method *methods = class_copyMethodList([Foo class], &methodCount);
  for (unsigned int i = 0; i < methodCount; i++) {
    Method m = methods[i];
    SEL selector = method_getName(m);
    const char *typeEncoding = method_getTypeEncoding(m);
    NSLog(@"%@\t%s", NSStringFromSelector(selector), typeEncoding);
  }
  free(methods);
  return 0;
}


package Nums;

use overload ('<=>' => \&compare);
sub new     { my $self = shift; bless [@_] }
sub flip    { my @a = @_; 1/$a }
sub double  { my @a = @_; 2*$a }
sub compare { my ($a, $b) = @_; abs($a) <=> abs($b) }

my $a = Nums->new(42);
print "$_\n" for %{ref ($a)."::" });


enum METHODS, PROPERTIES

sequence all_methods = {}

function method_visitor(object key, object /*data*/, /*user_data*/)
    all_methods = append(all_methods,key)
    return 1
end function

function get_all_methods(object o)
    all_methods = {}
    traverse_dict(method_visitor,0,o[METHODS])
    return all_methods
end function

function exists()
    return "exists"
end function

--class X: Xmethods emulates a vtable
constant Xmethods = new_dict({{"exists",exists}})

--class X: destructor
procedure destructor(object o)
    destroy_dict(o[PROPERTIES])
end procedure

--class X: create new instances
function newX(object x,y)
    integer Xproperties = new_dict({{"x",x},{"y",y}})
    object res = delete_routine({Xmethods,Xproperties},destructor)
    return res
end function

object x = newX(2,"string")

?get_all_methods(x)


' FB 1.05.0 Win64

Sub removeLines(fileName As String, startLine As UInteger, numLines As UInteger)
  If startLine = 0 Then
    Print "Starting line must be more than zero"
    Return
  End If
  If numLines = 0 Then
    Print "No lines to remove"
    Return
  End If
  Dim fileNum As Integer = FreeFile
  Open fileName For Input As #fileNum
  If err > 0 Then
    Print "File could not be opened"
    Return
  End If
  Dim tempFileName As String = "temp_" + fileName
  Dim fileNum2 As Integer = FreeFile
  Open tempFileName For Output As #fileNum2
  Dim count As Integer = 0
  Dim ln As String
  Dim endLine As UInteger = startLine + numLines - 1
  While Not Eof(fileNum)
    Input #fileNum, ln
    count += 1
    If count >= startLine AndAlso count <= endLine Then Continue While
    Print #fileNum2, ln
  Wend

  If count < startLine Then
    Print "No lines were removed as starting line was beyond end of file"
    Print
  ElseIf count < endLine Then
    Print "Only "; count - startLine + 1; " line(s) were removed as not enough lines to remove more"
    Print
  Else
    Print Str(numLines); " line(s) were removed"
    Print
  End If
  Close #fileNum : Close #fileNum2
  Kill(fileName)
  Name (tempFileName, fileName)
End Sub

removeLines("foobar.txt", 2, 2)
removeLines("foobar.txt", 5, 2)
removeLines("foobar.txt", 3, 4)
Print
Print "Press any key to quit"
Sleep