MODULE FileTest EXPORTS Main;

IMPORT IO, Fmt, FS, File, OSError, Pathname;

PROCEDURE FileExists(file: Pathname.T): BOOLEAN =
  VAR status: File.Status;
  BEGIN
    TRY
      status := FS.Status(file);
      RETURN TRUE;
    EXCEPT
    | OSError.E => RETURN FALSE;
    END;
  END FileExists;

BEGIN
  IO.Put(Fmt.Bool(FileExists("input.txt")) & "\n");
  IO.Put(Fmt.Bool(FileExists("/input.txt")) & "\n");
  IO.Put(Fmt.Bool(FileExists("docs/")) & "\n");
  IO.Put(Fmt.Bool(FileExists("/docs")) & "\n");
END FileTest.


import Nanoquery.IO

def exists(fname)
	f = new(File, fname)

	return f.exists()
end


/**
 Check that file/dir exists, in Neko
*/

var sys_exists = $loader.loadprim("[email protected]_exists", 1)
var sys_file_type = $loader.loadprim("[email protected]_file_type", 1)
var sys_command = $loader.loadprim("[email protected]_command", 1)

var name = "input.txt"
$print(name, " exists as file: ", sys_exists(name), "\n")

$print(name = "docs", " exists as dir: ", sys_exists(name) && sys_file_type(name) == "dir", "\n")
$print(name = "neko", " exists as dir: ", sys_exists(name) && sys_file_type(name) == "dir", "\n")

$print(name = "/input.txt", " exists as file: ", sys_exists(name) && sys_file_type(name) == "file", "\n")
$print(name = "/docs", " exists as dir: ", sys_exists(name) && sys_file_type(name) == "dir", "\n")
$print(name = "/tmp", " exists as dir: ", sys_exists(name) && sys_file_type(name) == "dir", "\n")

/* bonus round */
name = "empty.txt"
var stat_size = $loader.loadprim("[email protected]_stat", 1)(name).size
$print(name, " exists as empty file: ", sys_exists(name) && stat_size == 0, "\n")

name = "`Abdu'l-Bahá.txt"
$print(name, " exists as file: ", sys_exists(name) && sys_file_type(name) == "file", "\n")


using System.Console;
using System.IO;

WriteLine(File.Exists("input.txt"));
WriteLine(File.Exists("/input.txt"));
WriteLine(Directory.Exists("docs"));
WriteLine(Directory.Exists("/docs"));


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

runSample(arg)
return

-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method isExistingFile(fn) public static returns boolean
  ff = File(fn)
  fExists = ff.exists() & ff.isFile()
  return fExists

-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method isExistingDirectory(fn) public static returns boolean
  ff = File(fn)
  fExists = ff.exists() & ff.isDirectory()
  return fExists

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  parse arg files
  if files = '' then files = 'input.txt F docs D /input.txt F /docs D'
  loop while files.length > 0
    parse files fn ft files
    select case(ft.upper())
      when 'F' then do
        if isExistingFile(fn) then ex = 'exists'
        else                       ex = 'does not exist'
        say 'File '''fn'''' ex
        end
      when 'D' then do
        if isExistingDirectory(fn) then ex = 'exists'
        else                            ex = 'does not exist'
        say 'Directory '''fn'''' ex
        end
      otherwise do
        if isExistingFile(fn) then ex = 'exists'
        else                       ex = 'does not exist'
        say 'File '''fn'''' ex
        end
      end
    end

  return


(dolist (file '("input.txt" "/input.txt"))
  (if (file? file true)
      (println "file " file " exists")))

(dolist (dir '("docs" "/docs"))
  (if (directory? dir)
      (println "directory " dir " exists")))


import os

echo fileExists "input.txt"
echo fileExists "/input.txt"
echo dirExists "docs"
echo dirExists "/docs"


use IO;

bundle Default {
  class Test {
    function : Main(args : String[]) ~ Nil {
      File->Exists("input.txt")->PrintLine();
      File->Exists("/input.txt")->PrintLine();
      Directory->Exists("docs")->PrintLine();
      Directory->Exists("/docs")->PrintLine();
    }
}


NSFileManager *fm = [NSFileManager defaultManager];
NSLog(@"input.txt %s", [fm fileExistsAtPath:@"input.txt"] ? @"exists" : @"doesn't exist");
NSLog(@"docs %s", [fm fileExistsAtPath:@"docs"] ? @"exists" : @"doesn't exist");


Sys.file_exists "input.txt";;
Sys.file_exists "docs";;
Sys.file_exists "/input.txt";;
Sys.file_exists "/docs";;


/**********************************************************************
* exists(filespec)
* returns 1   if filespec identifies a file with size>0
*                (a file of size 0 is deemed not to exist.)
*             or a directory
*         0   otherwise
* 09.06.2013 Walter Pachl (retrieved from my toolset)
**********************************************************************/
exists:
  parse arg spec
  call sysfiletree spec, 'LIST', 'BL'
  if list.0\=1 then return 0        -- does not exist
  parse var list.1 . . size flags .
  if size>0 then return 1           -- real file
  If substr(flags,2,1)='D' Then Do
    Say spec 'is a directory'
    Return 1
    End
  If size=0 Then Say spec 'is a zero-size file'
  Return 0


declare
  [Path] = {Module.link ['x-oz://system/os/Path.ozf']}
in
  {Show {Path.exists "docs"}}
  {Show {Path.exists "input.txt"}}
  {Show {Path.exists "/docs"}}
  {Show {Path.exists "/input.txt"}}


trap(,"does not exist",read("input.txt");"exists")
trap(,"does not exist",read("c:\\input.txt");"exists")
trap(,"does not exist",read("c:\\dirname\\nul");"exists")


use File::Spec::Functions qw(catfile rootdir);
# here
print -e 'input.txt';
print -d 'docs';
# root dir
print -e catfile rootdir, 'input.txt';
print -d catfile rootdir, 'docs';


without js -- (file i/o)
procedure check(string name)
    bool bExists = file_exists(name),
         bDir = get_file_type(name)=FILETYPE_DIRECTORY
    string exists = iff(bExists?"exists":"does not exist"),
           dfs = iff(bExists?iff(bDir?"directory ":"file "):"")
    printf(1,"%s%s %s.\n",{dfs,name,exists})
end procedure

check("input.txt")
check("docs")
check("/input.txt")
check("/docs")
check("/pagefile.sys")
check("/Program Files (x86)")


"foo.bar" "w" fopen
"Hallo !" over fputs
fclose

"fou.bar" "r" fopen
dup 0 < if "Could not open 'foo.bar' for reading" print drop else fclose endif


if (file_exists('input.txt')) echo 'input.txt is here right by my side';
if (file_exists('docs'     )) echo 'docs is here with me';
if (file_exists('/input.txt')) echo 'input.txt is over there in the root dir';
if (file_exists('/docs'    )) echo 'docs is over there in the root dir';


(if (info "file.txt")
   (prinl "Size: " (car @) " bytes, last modified " (stamp (cadr @) (cddr @)))
   (prinl "File doesn't exist") )

# for directory existing
# Nehal-Singhal 2018-05-25

(if (info "./docs")
  (print 'exists)
  (print 'doesNotExist)))

# To verify if it's really a directory, (CAR of return value will be 'T').
# abu 2018-05-25

  (let I (info "./docs")
      (prinl
         (nond
            (I "Does not exist")
            ((=T (car I)) "Is not a directory")
            (NIL "Directory exists") ) ) )


import Stdio;

int main(){
   if(exist("/var")){
      write("/var exists!\n");
   }

   if(exist("file-exists.pike")){
      write("I exist!\n");
   }
}


*Process source or(!);
 /*********************************************************************
 * 20.10.2013 Walter Pachl
 * 'set dd:f=d:\_l\xxx.txt,recsize(300)'
 * 'tex'
 *********************************************************************/
 tex: Proc Options(main);
 Dcl fid Char(30) Var Init('D:\_l\tst.txt');
 Dcl xxx Char(30) Var Init('D:\_l\nix.txt');
 Dcl r   Char(1000) Var;
 Dcl f Record input;
 On Undefinedfile(f) Goto label;
 Open File(f) Title('/'!!fid);
 Read file(f) Into(r);
 Put Skip List('First line of file '!!fid!!': '!!r);
 Close File(f);
 Open File(f) Title('/'!!xxx);
 Read file(f) Into(r);
 Put Skip List(r);
 Close File(f);
 Label: Put Skip List('File '!!xxx!!' not found');
 End;


100H:

   DECLARE FCB$SIZE      LITERALLY '36';

   BDOS: PROCEDURE( FN, ARG )BYTE; /* CP/M BDOS SYSTEM CALL, RETURNS A VALUE */
      DECLARE FN BYTE, ARG ADDRESS;
      GOTO 5;
   END BDOS;
   BDOS$P: PROCEDURE( FN, ARG );   /* CP/M BDOS SYSTEM CALL, NO RETURN VALUE */
      DECLARE FN BYTE, ARG ADDRESS;
      GOTO 5;
   END BDOS$P;
   PRINT$CHAR:   PROCEDURE( C ); DECLARE C BYTE;    CALL BDOS$P( 2, C );   END;
   PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS$P( 9, S );   END;
   PRINT$NL:     PROCEDURE; CALL PRINT$STRING( .( 0DH, 0AH, '$' ) );       END;
   SEARCH$FIRST: PROCEDURE( FCB )BYTE;   /* RETURN 0, 1, 2, 3 IF FILE IN FCB */
      DECLARE FCB ADDRESS;               /*        EXISTS, 255 OTHERWISE     */
      RETURN BDOS( 17, FCB );
   END SEARCH$FIRST ;

   INIT$FCB: PROCEDURE( FCB, NAME );  /* INITIALISE A FILE-CONTROL-BLOCK     */
      DECLARE ( FCB, NAME ) ADDRESS;  /*     SETTING THE FILE NAME           */
      DECLARE ( F$PTR, N$PTR, X$PTR ) ADDRESS;
      DECLARE F BASED F$PTR BYTE, N BASED N$PTR BYTE;
      DECLARE BLANKS ( 5 )BYTE INITIAL( ' ', ' ', ' ', ' ', '$' );
      X$PTR = .BLANKS;
      N$PTR = NAME + 1;
      F$PTR = FCB;
      IF N <> ':' THEN DO;            /* NO DRIVE LETTER                     */
         F     = 0;
         N$PTR = NAME;
         END;
      ELSE DO;                        /* FIRST CHAR IS THE DRIVE LETTER      */
         N$PTR = NAME;
         F     = ( N + 1 ) - 'A';
         N$PTR = N$PTR + 2;
      END;
      DO F$PTR = FCB + 1 TO FCB + 8;  /* NAME                                */
         IF      N = '$' THEN N$PTR = .BLANKS;
         ELSE IF N = '.' THEN DO;     /* START OF THE EXTENSION              */
            X$PTR =  N$PTR + 1;
            N$PTR = .BLANKS;
         END;
         F     = N;
         N$PTR = N$PTR + 1;
      END;
      N$PTR = X$PTR;                  /* EXTENSION                           */
      DO F$PTR = FCB + 9 TO FCB + 11;
         IF N = '$' THEN N$PTR =.BLANKS;
         F     = N;
         N$PTR = N$PTR + 1;
      END;
      DO F$PTR = FCB + 12 TO FCB + ( FCB$SIZE - 1 ); /* OTHER FIELDS         */
         F = 0;
      END;
   END INIT$FCB ;

   EXISTS: PROCEDURE( FCB )BYTE; /* RETURNS TRUE IF THE FILE NAMED IN THE    */
      DECLARE FCB ADDRESS;       /*                 FCB EXISTS               */
      RETURN ( SEARCH$FIRST( FCB ) < 4 );
   END EXISTS ;

   DECLARE FCB$1$DATA ( FCB$SIZE )BYTE;  /* DECLARE A FILE-CONTROL-BLOCK     */
   DECLARE FCB$1 ADDRESS;
   FCB$1 = .FCB$1$DATA;

   /* CP/M DOES NOT HAVE DIRECTORIES/FOLDERS - THIS TESTS FOR INPUT.TXT IN   */
   /* THE CURRENT DEFAULT DRIVE                                              */
   CALL INIT$FCB( FCB$1, .'INPUT.TXT$' );
   CALL PRINT$STRING( .'INPUT.TXT: $' );
   IF EXISTS( FCB$1 ) THEN CALL PRINT$STRING( .'EXISTS$' );
                      ELSE CALL PRINT$STRING( .'DOES NOT EXIST$' );
   CALL PRINT$NL;

   /* CHECK FOR INPUT.TXT IN THE D: DRIVE                                    */
   /* !!! THIS WILL CAUSE AN ERROR IF THERE IS NO DRIVE D:               !!! */
   /* !!! OR THERE IS NO DISC IN DRIVE D:                                !!! */
   CALL INIT$FCB( FCB$1, .'D:INPUT.TXT$' );
   CALL PRINT$STRING( .'D:INPUT.TXT: $' );
   IF EXISTS( FCB$1 ) THEN CALL PRINT$STRING( .'EXISTS$' );
                      ELSE CALL PRINT$STRING( .'DOES NOT EXIST$' );
   CALL PRINT$NL;

EOF


sys_file_exists('input.txt') =>
sys_file_exists('/input.txt') =>
sys_file_exists('docs') =>
sys_file_exists('/docs') =>


 if (Test-Path -Path .\input.txt) {
   write-host "File input exist"
}
else {
   write-host "File input doesn't exist"
}


exists_file('input.txt'),
exists_directory('docs').

exits_file('/input.txt'),
exists_directory('/docs').


result = ReadFile(#PB_Any, "input.txt")
If result>0 : Debug "this local file exists"
  Else : Debug "result=" +Str(result) +" so this local file is missing"
EndIf

result = ReadFile(#PB_Any, "/input.txt")
If result>0 : Debug "this root file exists"
  Else : Debug "result=" +Str(result) +" so this root file is missing"
EndIf

result = ExamineDirectory(#PB_Any,"docs","")
If result>0 : Debug "this local directory exists"
  Else : Debug "result=" +Str(result) +" so this local directory is missing"
EndIf

result = ExamineDirectory(#PB_Any,"/docs","")
If result>0 : Debug "this root directory exists"
  Else : Debug "result=" +Str(result) +" so this root directory is missing"
EndIf


import os

os.path.isfile("input.txt")
os.path.isfile("/input.txt")
os.path.isdir("docs")
os.path.isdir("/docs")


$NOPREFIX
PRINT DIREXISTS("docs")
PRINT DIREXISTS("\docs")
PRINT FILEEXISTS("input.txt")
PRINT FILEEXISTS("\input.txt")


file.exists("input.txt")
file.exists("/input.txt")
file.exists("docs")
file.exists("/docs")

# or
file.exists("input.txt", "/input.txt", "docs", "/docs")


#lang racket

;; here
(file-exists? "input.txt")
(file-exists? "docs")

;; in the root
(file-exists? "/input.txt")
(file-exists? "/docs")

;; or in the root with relative paths
(parameterize ([current-directory "/"])
  (and (file-exists? "input.txt")
       (file-exists? "docs")))


my $path = "/etc/passwd";
say $path.IO.e ?? "Exists" !! "Does not exist";

given $path.IO {
    when :d { say "$path is a directory"; }
    when :f { say "$path is a regular file"; }
    when :e { say "$path is neither a directory nor a file, but it does exist"; }
    default { say "$path does not exist" }
}


'input.txt'  exists if 'input.txt exists'  print
'/input.txt' exists if '/input.txt exists' print
'docs'  isdir if 'docs exists and is a directory'  print
'/docs' isdir if '/docs exists and is a directory' print


exists? %input.txt
exists? %docs/

exists? %/input.txt
exists? %/docs/


exists? %input.txt
exists? %docs/
exists? %/c/input.txt
exists? %/c/docs/
exists? %//input.txt
exists? %//docs/

>> exists? %`Abdu'l-Bahá.txt
== true


/*REXX program creates a new empty file and directory in current directory and root dir.*/
fn= 'input.txt'                                  /*default name of a file.              */
dn= 'docs'                                       /*default name of a directory (folder).*/
@.1= 'current directory';  @.2= 'root directory' /*messages used to indicate which pass.*/
parse upper version v                            /*obtain name of the REXX being used.  */
regina= pos('REGINA'  , v)\==0                   /*is this the Regina REXX being used?  */
r4    = pos('REXX-R4' , v)\==0                   /*is this the R4     REXX being used?  */
@doesnt= "doesn't exist in the"
@does  = "does exist in the"

 do j=1  for 2;    say                           /* [↑]  perform these statements twice.*/
 if stream(fn, 'C', "QUERY EXISTS")==''  then say 'file '       fn   @doesnt   @.j
                                         else say 'file '       fn   @does     @.j

 if j==2  then iterate
 if stream(dn, 'C', "QUERY EXISTS")==''  then say 'directory'   dn   @doesnt   @.j
                                         else say 'directory'   dn   @does     @.j
 if j==1  then select
               when regina  then call chdir    '\'    /*use Regina's version of  CHDIR. */
               when r4      then call stream   '\', "C", 'CHDIR'        /*R4's version. */
               otherwise         call doschdir '\'    /*PC/REXX & Personal REXX version.*/
               end   /*select*/
 end   /*j*/                                     /*stick a fork in it,  we're all done. */


aFile = "C:\Ring\ReadMe.txt"
see aFile
if Fexists(aFile) see " exists" + nl
else see " doesn't exist" + nl ok


>> isdir("docs")
  0
>> isfile("input.txt")
  0


File.file?("input.txt")
File.file?("/input.txt")
File.directory?("docs")
File.directory?("/docs")


files #f,"input.txt"
if #f hasanswer() = 1 then print "File does not exist"
files #f,"docs"
if #f hasanswer() = 1 then print "File does not exist"
if #f isDir()     = 0 then print "This is a directory"


use std::fs;

fn main() {
    for file in ["input.txt", "docs", "/input.txt", "/docs"].iter() {
        match fs::metadata(file) {
            Ok(attr) => {
                if attr.is_dir() {
                    println!("{} is a directory", file);
                }else {
                    println!("{} is a file", file);
                }
            },
            Err(_) => {
                println!("{} does not exist", file);
            }
        };
    }
}


import java.nio.file.{ Files, FileSystems }

object FileExistsTest extends App {

  val defaultFS = FileSystems.getDefault()
  val separator = defaultFS.getSeparator()

  def test(filename: String) {
    val path = defaultFS.getPath(filename)

    println(s"The following ${if (Files.isDirectory(path)) "directory" else "file"} called $filename" +
      (if (Files.exists(path)) " exists." else " not exists."))
  }

  // main
  List("output.txt", separator + "output.txt", "docs", separator + "docs" + separator).foreach(test)
}


$ include "seed7_05.s7i";

const proc: main is func
  begin
    writeln(fileType("input.txt") = FILE_REGULAR);
    writeln(fileType("/input.txt") = FILE_REGULAR);
    writeln(fileType("docs") = FILE_DIR);
    writeln(fileType("/docs") = FILE_DIR);
  end func;


put file "input.txt" exists
put folder "docs" exists

put file "/input.txt" exists
put there is a folder "/docs"


# Here
say (Dir.cwd  + %f'input.txt' -> is_file);
say (Dir.cwd  + %d'docs'      -> is_dir);

# Root
say (Dir.root + %f'input.txt' -> is_file);
say (Dir.root + %d'docs'      -> is_dir);


(File newNamed: 'input.txt') exists
(File newNamed: '/input.txt') exists
(Directory root / 'input.txt') exists
(Directory newNamed: 'docs') exists
(Directory newNamed: '/docs') exists


FileDirectory new fileExists: 'c:\serial'.
(FileDirectory on: 'c:\') directoryExists: 'docs'.


OS.FileSys.access ("input.txt", []);
OS.FileSys.access ("docs", []);
OS.FileSys.access ("/input.txt", []);
OS.FileSys.access ("/docs", []);


mata
fileexists("input.txt")
direxists("docs")
end


if { [file exists "input.txt"] } {
    puts "input.txt exists"
}

if { [file exists [file nativename "/input.txt"]] } {
    puts "/input.txt exists"
}

if { [file isdirectory "docs"] } {
    puts "docs exists and is a directory"
}

if { [file isdirectory [file nativename "/docs"]] } {
    puts "/docs exists and is a directory"
}


[ "R" file.open dup 0 <> [ dup file.close ] ifTrue 0 <> ] is exists?
" input.txt" exists? .
" /input.txt" exists? .
" docs" exists? .
" /docs" exists? .


SUB opener (a$)
    WHEN EXCEPTION IN
         OPEN #1: NAME f$
         PRINT f$; " exists"
    USE
         PRINT f$; " not exists"
    END WHEN
    CLOSE #1
END SUB

LET f$ = "input.txt"
CALL opener (f$)
LET f$ = "\input.txt"
CALL opener (f$)
LET f$ = "docs\nul"
CALL opener (f$)
LET f$ = "\docs\nul"
CALL opener (f$)

LET f$ = "empty.tru"
CALL opener (f$)
LET f$ = "`Abdu'l-Bahá.txt"
CALL opener (f$)
END


$$ MODE TUSCRIPT
file="input.txt",directory="docs"
IF (file=='file') THEN
PRINT file, " exists"
ELSE
PRINT/ERROR file," not exists"
ENDIF
IF (directory=='project') THEN
PRINT directory," exists"
ELSE
PRINT/ERROR "directory ",directory," not exists"
ENDIF


test -f input.txt
test -f /input.txt
test -d docs
test -d /docs


def exists (string filename)
	decl file f
	try
		f.open filename
		return true
	catch ioerror
		return false
	end try
end exists


int main (string[] args) {
    string[] files = {"input.txt", "docs", Path.DIR_SEPARATOR_S + "input.txt", Path.DIR_SEPARATOR_S + "docs"};
    foreach (string f in files) {
        var file = File.new_for_path (f);
        print ("%s exists: %s\n", f, file.query_exists ().to_string ());
    }
    return 0;
}


Option Explicit

Sub Main_File_Exists()
Dim myFile As String, myDirectory As String

    myFile = "Abdu'l-Bahá.txt"
    myDirectory = "C:\"
    Debug.Print File_Exists(myFile, myDirectory)
End Sub

Function File_Exists(F As String, D As String) As Boolean
    If F = "" Then
        File_Exists = False
    Else
        D = IIf(Right(D, 1) = "\", D, D & "\")
        File_Exists = (Dir(D & F) <> "")
    End If
End Function


Set FSO = CreateObject("Scripting.FileSystemObject")

Function FileExists(strFile)
    If FSO.FileExists(strFile) Then
        FileExists = True
    Else
        FileExists = False
    End If
End Function

Function FolderExists(strFolder)
    If FSO.FolderExists(strFolder) Then
        FolderExists = True
    Else
        Folderexists = False
    End If
End Function

'''''Usage (apostrophes indicate comments-this section will not be run)'''''
'If FileExists("C:\test.txt") Then
'   MsgBox "It Exists!"
'Else
'   Msgbox "awww"
'End If
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

'Shorter version

If CreateObject("Scripting.FileSystemObject").FileExists("d:\test.txt") Then
    Wscript.Echo "File Exists"
Else
    Wscript.Echo "File Does Not Exist")
End If


// In current directory
if (File_Exist("input.txt")) { M("input.txt exists\n") } else { M("input.txt does not exist\n") }
if (File_Exist("docs/nul", NOERR)) { M("docs exists\n") } else { M("docs does not exist\n") }

// In the root directory
if (File_Exist("/input.txt")) { M("/input.txt exists\n") } else { M("/input.txt does not exist\n") }
if (File_Exist("/docs/nul", NOERR)) { M("/docs exists\n") } else { M("/docs does not exist\n") }


'declarations:
Public Declare Function GetFileAttributes Lib "kernel32" _
  Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Public Const INVALID_FILE_ATTRIBUTES As Long = -1
Public Const ERROR_SHARING_VIOLATION As Long = 32&

'implementation:
Public Function FileExists(ByVal Filename As String) As Boolean
Dim l As Long
l = GetFileAttributes(Filename)
  If l <> INVALID_FILE_ATTRIBUTES Then
    FileExists = ((l And vbDirectory) = 0)
  ElseIf Err.LastDllError = ERROR_SHARING_VIOLATION Then
    FileExists = True
  End If
End Function


'Current Directory
Console.WriteLine(If(IO.Directory.Exists("docs"), "directory exists", "directory doesn't exists"))
Console.WriteLine(If(IO.Directory.Exists("output.txt"), "file exists", "file doesn't exists"))

'Root
Console.WriteLine(If(IO.Directory.Exists("\docs"), "directory exists", "directory doesn't exists"))
Console.WriteLine(If(IO.Directory.Exists("\output.txt"), "file exists", "file doesn't exists"))

'Root, platform independent
Console.WriteLine(If(IO.Directory.Exists(IO.Path.DirectorySeparatorChar & "docs"), _
   "directory exists", "directory doesn't exists"))
Console.WriteLine(If(IO.Directory.Exists(IO.Path.DirectorySeparatorChar & "output.txt"), _
  "file exists", "file doesn't exists"))


// Check file exists in V
// Tectonics: v run check-that-file-exists.v
module main
import os

// starts here
pub fn main() {
    // file and directory checks
    _ := os.execute("touch input.txt")
    println("os.is_file('input.txt'): ${os.is_file('input.txt')}")

    // make doc directory in current dir if it doesn't exist
    _ := os.execute("mkdir -p doc")
    println("os.is_dir('doc'): ${os.is_dir('doc')}")

    // check in the root dir
    println("os.is_file('/input.txt'): ${os.is_file('/input.txt')}")
    println("os.is_dir('/doc'): ${os.is_dir('/doc')}")

    // check for file, with empty file
    _ := os.execute("truncate -s 0 empty.txt")
    println("os.is_file('empty.txt'): ${os.is_file('empty.txt')}")

    // check for file, with exotic name
    wfn := "`Abdu'l-Bahá.txt"
    efn := wfn.replace_each(["'", r"\'", "`", r"\`"])
    _ := os.execute('touch $efn')
    println('os.is_file("$wfn"): ${os.is_file(wfn)}')
}


import "io" for Directory, File

for (name in ["input.txt", "`Abdu'l-Bahá.txt"]) {
    if (File.exists(name)) {
        System.print("%(name) file exists and has a size of %(File.size(name)) bytes.")
    } else {
        System.print("%(name) file does not exist.")
    }
}

var dir = "docs"
// if it exists get number of files it contains
if (Directory.exists(dir)) {
    var files = Directory.list(dir).count
    System.print("%(dir) directory exists and contains %(files) files.")
} else {
    System.print("%(dir) directory does not exist.")
}


int FD;         \file descriptor
[Trap(false);	\prevent errors from aborting program
FD:= FOpen("input.txt", 0);
if GetErr then Text(0, "input.txt doesn't exist^m^j");
FD:= FOpen("dir", 0);
if GetErr then Text(0, "dir doesn't exist^m^j");
FD:= FOpen("/input.txt", 0);
if GetErr then Text(0, "/input.txt doesn't exist^m^j");
FD:= FOpen("/dir", 0);
if GetErr then Text(0, "/dir doesn't exist^m^j");
]


open "foo.bar" for writing as #1
print #1 "Hallo !"
close #1
if (not open(1,"foo.bar")) print "Could not open 'foo.bar' for reading"
close #1
if (not open(1,"buzz.bar")) print "Could not open 'buzz.bar' for reading"


File.exists("input.txt")  //--> True (in this case a sym link)
File.exists("/input.txt") //-->False
File.isDir("/")     //-->True
File.isDir("docs")  //-->False


import std.stdio, std.regex, std.conv, std.string, std.range,
       arithmetic_rational;

struct Pair { int x; Rational r; }

Pair[][] parseEquations(in string text) /*pure nothrow*/ {
    auto r = regex(r"\s*(?P<sign>[+-])?\s*(?:(?P<mul>\d+)\s*\*)?\s*" ~
                   r"arctan\((?P<num>\d+)/(?P<denom>\d+)\)");
    Pair[][] machins;
    foreach (const line; text.splitLines) {
        Pair[] formula;
        foreach (part; line.split("=")[1].matchAll(r)) {
            immutable mul = part["mul"],
                      num = part["num"],
                      denom = part["denom"];
            formula ~= Pair((part["sign"] == "-" ? -1 : 1) *
                            (mul.empty ? 1 : mul.to!int),
                            Rational(num.to!int,
                                     denom.empty ? 1 : denom.to!int));
        }
        machins ~= formula;
    }
    return machins;
}

Rational tans(in Pair[] xs) pure nothrow {
    static Rational tanEval(in int coef, in Rational f)
    pure nothrow {
        if (coef == 1)
            return f;
        if (coef < 0)
            return -tanEval(-coef, f);
        immutable a = tanEval(coef / 2, f),
                  b = tanEval(coef - coef / 2, f);
        return (a + b) / (1 - a * b);
    }

    if (xs.length == 1)
        return tanEval(xs[0].tupleof);
    immutable a = xs[0 .. $ / 2].tans,
              b = xs[$ / 2 .. $].tans;
    return (a + b) / (1 - a * b);
}

void main() {
    immutable equationText =
"pi/4 = arctan(1/2) + arctan(1/3)
pi/4 = 2*arctan(1/3) + arctan(1/7)
pi/4 = 4*arctan(1/5) - arctan(1/239)
pi/4 = 5*arctan(1/7) + 2*arctan(3/79)
pi/4 = 5*arctan(29/278) + 7*arctan(3/79)
pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)
pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)
pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)
pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)
pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)
pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)
pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)
pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)
pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)
pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)";

    const machins = equationText.parseEquations;
    foreach (const machin, const eqn; machins.zip(equationText.splitLines)) {
        immutable ans = machin.tans;
        writefln("%5s: %s", ans == 1 ? "OK" : "ERROR", eqn);
    }
}


(lib 'math)
(lib 'match)
(math-precision 1.e-10)

;; formally derive (tan ..) expressions
;; copied from Racket
;; adapted and improved for performance

(define (reduce e)
;; (set! rcount (1+ rcount)) ;; # of calls
  (match e
    [(? number? a)                         a]
    [('+ (? number? a) (? number? b)) (+ a b)]
    [('- (? number? a) (? number? b)) (- a b)]
    [('- (? number? a))               (- a)]
    [('* (? number? a) (? number? b)) (* a b)]
    [('/ (? number? a) (? number? b)) (/ a b)] ; patch

    [( '+ a b)                         (reduce `(+ ,(reduce a) ,(reduce b)))]
    [( '- a b)                         (reduce `(- ,(reduce a) ,(reduce b)))]
    [( '- a)                           (reduce `(- ,(reduce a)))]
    [( '* a b)                         (reduce `(* ,(reduce a) ,(reduce b)))]
    [( '/ a b)                         (reduce `(/ ,(reduce a) ,(reduce b)))]

    [( 'tan ('arctan a))           (reduce a)]
    [( 'tan ( '- a))               (reduce `(- (tan ,a)))]

    ;; x 100 # calls reduction : derive (tan ,a) only once
    [( 'tan ( '+ a b))
          (let ((alpha (reduce  `(tan ,a))) (beta (reduce  `(tan ,b))))
    	  (reduce `(/ (+ ,alpha ,beta) (- 1 (* ,alpha ,beta)))))]

    [( 'tan ( '+ a b c ...))       (reduce `(tan (+ ,a (+ ,b ,@c))))]

    [( 'tan ( '- a b))
                (let ((alpha (reduce  `(tan ,a))) (beta (reduce  `(tan ,b))))
    		(reduce `(/ (- ,alpha ,beta) (+ 1 (* ,alpha ,beta)))))]

    ;; add formula for (tan 2 (arctan a)) = 2 a / (1 - a^2))
    [( 'tan ( '* 2 ('arctan a)))   (reduce `(/ (* 2 ,a) (- 1 (* ,a ,a))))]
    [( 'tan ( '* 1 ('arctan a)))   (reduce a)] ; added

    [( 'tan ( '* (? number? n) a))
     (cond [(< n 0) (reduce `(- (tan (* ,(- n) ,a))))]
           [(= n 0) 0]
           [(= n 1)    (reduce `(tan ,a))]
           [(even? n)
              (let ((alpha (reduce  `(tan (* ,(/ n 2) ,a))))) ;; # calls reduction
    	      (reduce `(/ (* 2 ,alpha) (- 1 (* ,alpha ,alpha)))))]
           [else      (reduce `(tan (+ ,a  (* ,(- n 1) ,a))))])]
    ))

(define (task)
	(for ((f machins))
	(if (~= 1 (reduce f))
		(writeln '👍 f  '⟾ 1 )
		(writeln '❌ f '➽ (reduce f) ))))


import Data.Ratio
import Data.List (foldl')

tanPlus :: Fractional a => a -> a -> a
tanPlus a b = (a + b) / (1 - a * b)

tanEval :: (Integral a, Fractional b) => (a, b) -> b
tanEval (0,_) = 0
tanEval (coef,f)
	| coef < 0 = -tanEval (-coef, f)
	| odd coef = tanPlus f $ tanEval (coef - 1, f)
	| otherwise = tanPlus a a
		where a = tanEval (coef `div` 2, f)

tans :: (Integral a, Fractional b) => [(a, b)] -> b
tans = foldl' tanPlus 0 . map tanEval

machins = [
	[(1, 1%2), (1, 1%3)],
	[(2, 1%3), (1, 1%7)],
	[(12, 1%18), (8, 1%57), (-5, 1%239)],
	[(88, 1%172), (51, 1%239), (32 , 1%682), (44, 1%5357), (68, 1%12943)]]

not_machin = [(88, 1%172), (51, 1%239), (32 , 1%682), (44, 1%5357), (68, 1%12944)]

main = do
	putStrLn "Machins:"
	mapM_ (\x -> putStrLn $ show (tans x) ++ " <-- " ++ show x) machins

	putStr "\nnot Machin: "; print not_machin
	print (tans not_machin)


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckMachinFormula {

    private static String FILE_NAME = "MachinFormula.txt";

    public static void main(String[] args) {
        try {
            runPrivate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void runPrivate() throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {
            String inLine = null;
            while ( (inLine = reader.readLine()) != null ) {
                String[] split = inLine.split("=");
                System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim()));
            }
        }
    }

    private static String tanLeft(String formula) {
        if ( formula.compareTo("pi/4") == 0 ) {
            return "1";
        }
        throw new RuntimeException("ERROR 104:  Unknown left side: " + formula);
    }

    private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)");

    private static Fraction tanRight(String formula) {
        Matcher matcher = ARCTAN_PATTERN.matcher(formula);
        List<Term> terms = new ArrayList<>();
        while ( matcher.find() ) {
            terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));
        }
        return evaluateArctan(terms);
    }

    private static Fraction evaluateArctan(List<Term> terms) {
        if ( terms.size() == 1 ) {
            Term term = terms.get(0);
            return evaluateArctan(term.coefficient, term.fraction);
        }
        int size = terms.size();
        List<Term> left = terms.subList(0, (size+1) / 2);
        List<Term> right = terms.subList((size+1) / 2, size);
        return arctanFormula(evaluateArctan(left), evaluateArctan(right));
    }

    private static Fraction evaluateArctan(int coefficient, Fraction fraction) {
        //System.out.println("C = " + coefficient + ", F = " + fraction);
        if ( coefficient == 1 ) {
            return fraction;
        }
        else if ( coefficient < 0 ) {
            return evaluateArctan(-coefficient, fraction).negate();
        }
        if ( coefficient % 2 == 0 ) {
            Fraction f = evaluateArctan(coefficient/2, fraction);
            return arctanFormula(f, f);
        }
        Fraction a = evaluateArctan(coefficient/2, fraction);
        Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);
        return arctanFormula(a, b);
    }

    private static Fraction arctanFormula(Fraction f1, Fraction f2) {
        return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));
    }

    private static class Fraction {

        public static final Fraction ONE = new Fraction("1", "1");

        private BigInteger numerator;
        private BigInteger denominator;

        public Fraction(String num, String den) {
            numerator = new BigInteger(num);
            denominator = new BigInteger(den);
        }

        public Fraction(BigInteger num, BigInteger den) {
            numerator = num;
            denominator = den;
        }

        public Fraction negate() {
            return new Fraction(numerator.negate(), denominator);
        }

        public Fraction add(Fraction f) {
            BigInteger gcd = denominator.gcd(f.denominator);
            BigInteger first = numerator.multiply(f.denominator.divide(gcd));
            BigInteger second = f.numerator.multiply(denominator.divide(gcd));
            return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));
        }

        public Fraction subtract(Fraction f) {
            return add(f.negate());
        }

        public Fraction multiply(Fraction f) {
            BigInteger num = numerator.multiply(f.numerator);
            BigInteger den = denominator.multiply(f.denominator);
            BigInteger gcd = num.gcd(den);
            return new Fraction(num.divide(gcd), den.divide(gcd));
        }

        public Fraction divide(Fraction f) {
            return multiply(new Fraction(f.denominator, f.numerator));
        }

        @Override
        public String toString() {
            if ( denominator.compareTo(BigInteger.ONE) == 0 ) {
                return numerator.toString();
            }
            return numerator + " / " + denominator;
        }
    }

    private static class Term {

        private int coefficient;
        private Fraction fraction;

        public Term(int c, Fraction f) {
            coefficient = c;
            fraction = f;
        }
    }

}


using AbstractAlgebra # implements arbitrary precision rationals

tanplus(x,y) = (x + y) / (1 - x * y)

function taneval(coef, frac)
    if coef == 0
        return 0
    elseif coef < 0
        return -taneval(-coef, frac)
    elseif isodd(coef)
        return tanplus(frac, taneval(coef - 1, frac))
    else
        x = taneval(div(coef, 2), frac)
        return tanplus(x, x)
    end
end

taneval(tup::Tuple) = taneval(tup[1], tup[2])

tans(v::Vector{Tuple{BigInt, Rational{BigInt}}}) = foldl(tanplus, map(taneval, v), init=0)

const testmats = Dict{Vector{Tuple{BigInt, Rational{BigInt}}}, Bool}([
    ([(1, 1//2), (1, 1//3)], true), ([(2, 1//3), (1, 1//7)], true),
    ([(12, 1//18), (8, 1//57), (-5, 1//239)], true),
    ([(88, 1//172), (51, 1//239), (32, 1//682), (44, 1//5357), (68, 1//12943)], true),
    ([(88, 1//172), (51, 1//239), (32, 1//682), (44, 1//5357), (68, 1//12944)], false)])

function runtestmats()
    println("Testing matrices:")
    for (k, m) in testmats
        ans = tans(k)
        println((ans == 1) == m ? "Verified as $m: " : "Not Verified as $m: ", "tan $k = $ans")
    end
end

runtestmats()


// version 1.1.3

import java.math.BigInteger

val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE

class BigRational : Comparable<BigRational> {

    val num: BigInteger
    val denom: BigInteger

    constructor(n: BigInteger, d: BigInteger) {
        require(d != bigZero)
        var nn = n
        var dd = d
        if (nn == bigZero) {
            dd = bigOne
        }
        else if (dd < bigZero) {
            nn = -nn
            dd = -dd
        }
        val g = nn.gcd(dd)
        if (g > bigOne) {
            nn /= g
            dd /= g
        }
        num = nn
        denom = dd
    }

    constructor(n: Long, d: Long) : this(BigInteger.valueOf(n), BigInteger.valueOf(d))

    operator fun plus(other: BigRational) =
        BigRational(num * other.denom + denom * other.num, other.denom * denom)

    operator fun unaryMinus() = BigRational(-num, denom)

    operator fun minus(other: BigRational) = this + (-other)

    operator fun times(other: BigRational) = BigRational(this.num * other.num, this.denom * other.denom)

    fun inverse(): BigRational {
        require(num != bigZero)
        return BigRational(denom, num)
    }

    operator fun div(other: BigRational) = this * other.inverse()

    override fun compareTo(other: BigRational): Int {
        val diff = this - other
        return when {
            diff.num < bigZero -> -1
            diff.num > bigZero -> +1
            else               ->  0
        }
    }

    override fun equals(other: Any?): Boolean {
       if (other == null || other !is BigRational) return false
       return this.compareTo(other) == 0
    }

    override fun toString() = if (denom == bigOne) "$num" else "$num/$denom"

    companion object {
        val ZERO = BigRational(bigZero, bigOne)
        val ONE  = BigRational(bigOne, bigOne)
    }
}

/** represents a term of the form: c * atan(n / d) */
class Term(val c: Long, val n: Long, val d: Long) {

    override fun toString() = when {
        c ==  1L   -> " + "
        c == -1L   -> " - "
        c <   0L   -> " - ${-c}*"
        else       -> " + $c*"
    } + "atan($n/$d)"
}

val one = BigRational.ONE

fun tanSum(terms: List<Term>): BigRational {
    if (terms.size == 1) return tanEval(terms[0].c, BigRational(terms[0].n, terms[0].d))
    val half = terms.size / 2
    val a = tanSum(terms.take(half))
    val b = tanSum(terms.drop(half))
    return (a + b) / (one - (a * b))
}

fun tanEval(c: Long, f: BigRational): BigRational {
    if (c == 1L)  return f
    if (c < 0L) return -tanEval(-c, f)
    val ca = c / 2
    val cb = c - ca
    val a = tanEval(ca, f)
    val b = tanEval(cb, f)
    return (a + b) / (one - (a * b))
}

fun main(args: Array<String>) {
    val termsList = listOf(
        listOf(Term(1, 1, 2), Term(1, 1, 3)),
        listOf(Term(2, 1, 3), Term(1, 1, 7)),
        listOf(Term(4, 1, 5), Term(-1, 1, 239)),
        listOf(Term(5, 1, 7), Term(2, 3, 79)),
        listOf(Term(5, 29, 278), Term(7, 3, 79)),
        listOf(Term(1, 1, 2), Term(1, 1, 5), Term(1, 1, 8)),
        listOf(Term(4, 1, 5), Term(-1, 1, 70), Term(1, 1, 99)),
        listOf(Term(5, 1, 7), Term(4, 1, 53), Term(2, 1, 4443)),
        listOf(Term(6, 1, 8), Term(2, 1, 57), Term(1, 1, 239)),
        listOf(Term(8, 1, 10), Term(-1, 1, 239), Term(-4, 1, 515)),
        listOf(Term(12, 1, 18), Term(8, 1, 57), Term(-5, 1, 239)),
        listOf(Term(16, 1, 21), Term(3, 1, 239), Term(4, 3, 1042)),
        listOf(Term(22, 1, 28), Term(2, 1, 443), Term(-5, 1, 1393), Term(-10, 1, 11018)),
        listOf(Term(22, 1, 38), Term(17, 7, 601), Term(10, 7, 8149)),
        listOf(Term(44, 1, 57), Term(7, 1, 239), Term(-12, 1, 682), Term(24, 1, 12943)),
        listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12943)),
        listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12944))
    )

    for (terms in termsList) {
        val f = String.format("%-5s << 1 == tan(", tanSum(terms) == one)
        print(f)
        print(terms[0].toString().drop(3))
        for (i in 1 until terms.size) print(terms[i])
        println(")")
    }
}


import bignum

type

  # Description of a term.
  Term = object
    factor: int    # Multiplier (may be negative).
    fract: Rat     # Argument of arc tangent.

  Expression = seq[Term]

# Rational 1.
let One = newRat(1)

####################################################################################################
# Formula parser.

type

  # Possible tokens for parsing.
  Token = enum tkPi, tkArctan, tkNumber, tkEqual, tkAdd, tkSub,
               tkMul, tkDiv, tkLPar, tkRPar, tkError, tkEnd

  # Lexer description.
  Lexer = object
    line: string      # The line to parse.
    pos: Natural      # Current position of lexer.
    token: Token      # Current token.
    value: Natural    # Associated value (for numbers).

  # Exception raised if an error is found.
  SyntaxError = object of CatchableError

#---------------------------------------------------------------------------------------------------

proc initLexer(line: string): Lexer =
  ## Create and initialize a lexer.
  result.line = line
  result.pos = 0

#---------------------------------------------------------------------------------------------------

proc parseName(lexer: var Lexer; pos: Natural) =
  ## Parse a name.

  # Build the name.
  var pos = pos
  var name = ""
  while pos < lexer.line.len and (let c = lexer.line[pos]; c) in 'a'..'z':
    name.add(c)
    inc pos

  # Update lexer state.
  lexer.token = if name == "arctan": tkArctan
                elif name == "pi": tkPi
                else: tkError
  lexer.pos = pos

#---------------------------------------------------------------------------------------------------

proc parseNumber(lexer: var Lexer; pos: Natural) =
  ## Parse a number.

  # Build the number.
  var pos = pos
  var value = 0
  while pos < lexer.line.len and (let c = lexer.line[pos]; c) in '0'..'9':
    value = 10 * value + ord(c) - ord('0')
    inc pos

  # Update lexer state.
  lexer.token = tkNumber
  lexer.value = value
  lexer.pos = pos

#---------------------------------------------------------------------------------------------------

proc getNextToken(lexer: var Lexer) =
  ## Find next token.

  var pos = lexer.pos
  var token: Token
  while pos < lexer.line.len and lexer.line[pos] == ' ': inc pos
  if pos == lexer.line.len:
    # Reached end of string.
    lexer.pos = pos
    lexer.token = tkEnd
    return

  # Find token.
  case lexer.line[pos]
  of '=': token = tkEqual
  of '+': token = tkAdd
  of '-': token = tkSub
  of '*': token = tkMul
  of '/': token = tkDiv
  of '(': token = tkLPar
  of ')': token = tkRPar
  of 'a'..'z':
    lexer.parseName(pos)
    return
  of '0'..'9':
    lexer.parseNumber(pos)
    return
  else: token = tkError

  # Update lexer state.
  lexer.pos = pos + 1
  lexer.token = token

#---------------------------------------------------------------------------------------------------

template syntaxError(message: string) =
  ## Raise a syntax error exception.
  raise newException(SyntaxError, message)

#---------------------------------------------------------------------------------------------------

proc parseFraction(lexer: var Lexer): Rat =
  ## Parse a fraction: number / number.

  lexer.getNextToken()
  if lexer.token != tkNumber:
    syntaxError("number expected.")
  let num = lexer.value
  lexer.getNextToken()
  if lexer.token != tkDiv:
    syntaxError("“/” expected.")
  lexer.getNextToken()
  if lexer.token != tkNumber:
    syntaxError("number expected")
  if lexer.value == 0:
    raise newException(ValueError, "null denominator.")
  let den = lexer.value
  result = newRat(num, den)

#---------------------------------------------------------------------------------------------------

proc parseTerm(lexer: var Lexer): Term =
  ## Parse a term: factor * arctan(fraction) or arctan(fraction).

  lexer.getNextToken()

  # Parse factor.
  if lexer.token == tkNumber:
    result.factor = lexer.value
    lexer.getNextToken
    if lexer.token != tkMul:
      syntaxError("“*” expected.")
    lexer.getNextToken()
  else:
    result.factor = 1

  # Parse arctan.
  if lexer.token != tkArctan:
    syntaxError("“arctan” expected.")
  lexer.getNextToken()
  if lexer.token != tkLPar:
    syntaxError("“(” expected.")
  result.fract = lexer.parseFraction()
  lexer.getNextToken()
  if lexer.token != tkRPar:
    syntaxError("“)” expected.")

#---------------------------------------------------------------------------------------------------

proc parse(line: string): Expression =
  ## Parse a formula.

  var lexer = initLexer(line)
  lexer.getNextToken()

  if lexer.token != tkPi:
    syntaxError("pi symbol expected.")
  lexer.getNextToken()

  if lexer.token != tkDiv:
    syntaxError("'/' expected.")
  lexer.getNextToken()

  if lexer.token != tkNumber:
    syntaxError("number expected.")
  if lexer.value != 4:
    raise newException(ValueError, "value 4 expected.")
  lexer.getNextToken()

  if lexer.token != tkEqual:
    syntaxError("“=” expected.")
  result.add(lexer.parseTerm())
  lexer.getNextToken()

  # Parse the next terms.
  while (let token = lexer.token; token) in {tkAdd, tkSub}:
    var term = lexer.parseTerm()
    if token == tkSub:
      term.factor = -term.factor
    result.add(term)
    lexer.getNextToken()

  if lexer.token != tkEnd:
    syntaxError("invalid characters at end of formula.")

####################################################################################################
# Evaluator.

proc tangent(factor: int; fract: Rat): Rat =
  ## Compute the tangent of "factor * arctan(fract)".

  if factor == 1:
    return fract
  if factor < 0:
    return -tangent(-factor, fract)

  # Split in two parts.
  let n = factor div 2
  let a = tangent(n, fract)
  let b = tangent(factor - n, fract)
  result = (a + b) / (One - a * b)

#---------------------------------------------------------------------------------------------------

proc tangent(expr: Expression): Rat =
  ## Compute the tangent of a sum of terms.

  if expr.len == 1:
    result = tangent(expr[0].factor, expr[0].fract)
  else:
    # Split in two parts.
    let a = tangent(expr[0..<(expr.len div 2)])
    let b = tangent(expr[(expr.len div 2)..^1])
    result = (a + b) / (One - a * b)

#———————————————————————————————————————————————————————————————————————————————————————————————————

when isMainModule:

  const Formulas = [
    "pi/4 = arctan(1/2) + arctan(1/3)",
    "pi/4 = 2*arctan(1/3) + arctan(1/7)",
    "pi/4 = 4*arctan(1/5) - arctan(1/239)",
    "pi/4 = 5*arctan(1/7) + 2*arctan(3/79)",
    "pi/4 = 5*arctan(29/278) + 7*arctan(3/79)",
    "pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)",
    "pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)",
    "pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)",
    "pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)",
    "pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)",
    "pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)",
    "pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)",
    "pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)",
    "pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)",
    "pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)",
    "pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)",
    "pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)"]

for formula in Formulas:
  let expr = formula.parse()
  let value = tangent(expr)
  if value == 1:
    echo "True:  ", formula
  else:
    echo "False: ", formula
    echo "Tangent of the right expression is about ", value.toFloat


import re
from fractions import Fraction
from pprint import pprint as pp

equationtext = '''\
  pi/4 = arctan(1/2) + arctan(1/3)
  pi/4 = 2*arctan(1/3) + arctan(1/7)
  pi/4 = 4*arctan(1/5) - arctan(1/239)
  pi/4 = 5*arctan(1/7) + 2*arctan(3/79)
  pi/4 = 5*arctan(29/278) + 7*arctan(3/79)
  pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)
  pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)
  pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)
  pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)
  pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)
  pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)
  pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)
  pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)
  pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)
  pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)
  pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)
  pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)
'''

def parse_eqn(equationtext=equationtext):
    eqn_re = re.compile(r"""(?mx)
    (?P<lhs> ^ \s* pi/4 \s* = \s*)?             # LHS of equation
    (?:                                         # RHS
        \s* (?P<sign> [+-])? \s*
        (?: (?P<mult> \d+) \s* \*)?
        \s* arctan\( (?P<numer> \d+) / (?P<denom> \d+)
    )""")

    found = eqn_re.findall(equationtext)
    machins, part = [], []
    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):
        if lhs and part:
            machins.append(part)
            part = []
        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),
                       Fraction(int(numer), (int(denom) if denom else 1)) ) )
    machins.append(part)
    return machins

def tans(xs):
    xslen = len(xs)
    if xslen == 1:
        return tanEval(*xs[0])
    aa, bb = xs[:xslen//2], xs[xslen//2:]
    a, b = tans(aa), tans(bb)
    return (a + b) / (1 - a * b)

def tanEval(coef, f):
    if coef == 1:
        return f
    if coef < 0:
        return -tanEval(-coef, f)
    ca = coef // 2
    cb = coef - ca
    a, b = tanEval(ca, f), tanEval(cb, f)
    return (a + b) / (1 - a * b)

if __name__ == '__main__':
    machins = parse_eqn()
    #pp(machins, width=160)
    for machin, eqn in zip(machins, equationtext.split('\n')):
        ans = tans(machin)
        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))


#lang R
library(Rmpfr)
prec <- 1000 # precision in bits
`%:%` <- function(e1, e2) '/'(mpfr(e1, prec), mpfr(e2, prec)) # operator %:% for high precision division
# function for checking identity of tan of expression and 1, making use of high precision division operator %:%
tanident_1 <- function(x) identical(round(tan(eval(parse(text = gsub("/", "%:%", deparse(substitute(x)))))), (prec/10)), mpfr(1, prec))


#lang racket
(define (reduce e)
  (match e
    [(? number? a)                         a]
    [(list '+ (? number? a) (? number? b)) (+ a b)]
    [(list '- (? number? a) (? number? b)) (- a b)]
    [(list '- (? number? a))               (- a)]
    [(list '* (? number? a) (? number? b)) (* a b)]
    [(list '/ (? number? a) (? number? b)) (/ a b)]
    [(list '+ a b)                         (reduce `(+ ,(reduce a) ,(reduce b)))]
    [(list '- a b)                         (reduce `(- ,(reduce a) ,(reduce b)))]
    [(list '- a)                           (reduce `(- ,(reduce a)))]
    [(list '* a b)                         (reduce `(* ,(reduce a) ,(reduce b)))]
    [(list '/ a b)                         (reduce `(/ ,(reduce a) ,(reduce b)))]
    [(list 'tan (list 'arctan a))          (reduce a)]
    [(list 'tan (list '- a))               (reduce `(- ,(reduce `(tan ,a))))]
    [(list 'tan (list '+ a b))             (reduce `(/ (+ (tan ,a) (tan ,b))
                                                       (- 1 (* (tan ,a) (tan ,b)))))]
    [(list 'tan (list '+ a b c ...))       (reduce `(tan (+ ,a (+ ,b ,@c))))]
    [(list 'tan (list '- a b))             (reduce `(/ (+ (tan ,a) (tan (- ,b)))
                                                       (- 1 (* (tan ,a) (tan (- ,b))))))]
    [(list 'tan (list '* 1 a))             (reduce `(tan ,a))]
    [(list 'tan (list '* (? number? n) a))
     (cond [(< n 0) (reduce `(- (tan (* ,(- n) ,a))))]
           [(= n 0) 0]
           [(even? n) (reduce `(tan (+ (* ,(/ n 2) ,a) (* ,(/ n 2) ,a))))]
           [else      (reduce `(tan (+ ,a  (* ,(- n 1) ,a))))])]))

(define correct-formulas
  '((tan (+ (arctan 1/2) (arctan 1/3)))
    (tan (+ (* 2 (arctan 1/3)) (arctan 1/7)))
    (tan (- (* 4 (arctan 1/5)) (arctan 1/239)))
    (tan (+ (* 5 (arctan 1/7)) (* 2 (arctan 3/79))))
    (tan (+ (* 5 (arctan 29/278)) (* 7 (arctan 3/79))))
    (tan (+ (arctan 1/2) (arctan 1/5) (arctan 1/8)))
    (tan (+ (* 4 (arctan 1/5)) (* -1 (arctan 1/70)) (arctan 1/99)))
    (tan (+ (* 5 (arctan 1/7)) (* 4 (arctan 1/53)) (* 2 (arctan 1/4443))))
    (tan (+ (* 6 (arctan 1/8)) (* 2 (arctan 1/57)) (arctan 1/239)))
    (tan (+ (* 8 (arctan 1/10)) (* -1 (arctan 1/239)) (* -4 (arctan 1/515))))
    (tan (+ (* 12 (arctan 1/18)) (* 8 (arctan 1/57)) (* -5 (arctan 1/239))))
    (tan (+ (* 16 (arctan 1/21)) (* 3 (arctan 1/239)) (* 4 (arctan 3/1042))))
    (tan (+ (* 22 (arctan 1/28)) (* 2 (arctan 1/443)) (* -5 (arctan 1/1393)) (* -10 (arctan 1/11018))))
    (tan (+ (* 22 (arctan 1/38)) (* 17 (arctan 7/601)) (* 10 (arctan 7/8149))))
    (tan (+ (* 44 (arctan 1/57)) (* 7 (arctan 1/239)) (* -12 (arctan 1/682)) (* 24 (arctan 1/12943))))
    (tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682))
            (* 44 (arctan 1/5357)) (* 68 (arctan 1/12943))))))

(define wrong-formula
  '(tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682))
           (* 44 (arctan 1/5357)) (* 68 (arctan 1/12944)))))

(displayln "Do all correct formulas reduce to 1?")
(for/and ([f correct-formulas]) (= 1 (reduce f)))

(displayln "The incorrect formula reduces to:")
(reduce wrong-formula)


package require Tcl 8.5

# Compute tan(atan(p)+atan(q)) using rationals
proc tadd {p q} {
    lassign $p pp pq
    lassign $q qp qq
    set topp [expr {$pp*$qq + $qp*$pq}]
    set topq [expr {$pq*$qq}]
    set prodp [expr {$pp*$qp}]
    set prodq [expr {$pq*$qq}]
    set lowp [expr {$prodq - $prodp}]
    set resultp [set gcd1 [expr {$topp * $prodq}]]
    set resultq [set gcd2 [expr {$topq * $lowp}]]
    # Critical! Normalize using the GCD
    while {$gcd2 != 0} {
	lassign [list $gcd2 [expr {$gcd1 % $gcd2}]] gcd1 gcd2
    }
    list [expr {$resultp / abs($gcd1)}] [expr {$resultq / abs($gcd1)}]
}
proc termTan {n a b} {
    if {$n < 0} {
	set n [expr {-$n}]
	set a [expr {-$a}]
    }
    if {$n == 1} {
	return [list $a $b]
    }
    set k [expr {$n - [set m [expr {$n / 2}]]*2}]
    set t2 [termTan $m $a $b]
    set m2 [tadd $t2 $t2]
    if {$k == 0} {
	return $m2
    }
    return [tadd [termTan $k $a $b] $m2]
}
proc machinTan {terms} {
    set sum {0 1}
    foreach term $terms {
	set sum [tadd $sum [termTan {*}$term]]
    }
    return $sum
}

# Assumes that the formula is in the very specific form below!
proc parseFormula {formula} {
    set RE {(-?\s*\d*\s*\*?)\s*arctan\s*\(\s*(-?\s*\d+)\s*/\s*(-?\s*\d+)\s*\)}
    set nospace {" " "" "*" ""}
    foreach {all n a b} [regexp -inline -all $RE $formula] {
	if {![regexp {\d} $n]} {append n 1}
	lappend result [list [string map $nospace $n] [string map $nospace $a] [string map $nospace $b]]
    }
    return $result
}

foreach formula {
    "pi/4 = arctan(1/2) + arctan(1/3)"
    "pi/4 = 2*arctan(1/3) + arctan(1/7)"
    "pi/4 = 4*arctan(1/5) - arctan(1/239)"
    "pi/4 = 5*arctan(1/7) + 2*arctan(3/79)"
    "pi/4 = 5*arctan(29/278) + 7*arctan(3/79)"
    "pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)"
    "pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)"
    "pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)"
    "pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)"
    "pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)"
    "pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)"
    "pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)"
    "pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)"
    "pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)"
    "pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)"
    "pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)"
    "pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)"
} {
    if {[tcl::mathop::== {*}[machinTan [parseFormula $formula]]]} {
	puts "Yes! '$formula' is true"
    } else {
	puts "No! '$formula' not true"
    }
}


Imports System.Numerics

Public Class BigRat ' Big Rational Class constructed with BigIntegers
    Implements IComparable
    Public nu, de As BigInteger
    Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),
                  One = New BigRat(BigInteger.One, BigInteger.One)
    Sub New(bRat As BigRat)
        nu = bRat.nu : de = bRat.de
    End Sub
    Sub New(n As BigInteger, d As BigInteger)
        If d = BigInteger.Zero Then _
            Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d)))
        Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)
        If bi > BigInteger.One Then n /= bi : d /= bi
        If d < BigInteger.Zero Then n = -n : d = -d
        nu = n : de = d
    End Sub
    Shared Operator -(x As BigRat) As BigRat
        Return New BigRat(-x.nu, x.de)
    End Operator
    Shared Operator +(x As BigRat, y As BigRat)
        Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)
    End Operator
    Shared Operator -(x As BigRat, y As BigRat) As BigRat
        Return x + (-y)
    End Operator
    Shared Operator *(x As BigRat, y As BigRat) As BigRat
        Return New BigRat(x.nu * y.nu, x.de * y.de)
    End Operator
    Shared Operator /(x As BigRat, y As BigRat) As BigRat
        Return New BigRat(x.nu * y.de, x.de * y.nu)
    End Operator
    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
        Dim dif As BigRat = New BigRat(nu, de) - obj
        If dif.nu < BigInteger.Zero Then Return -1
        If dif.nu > BigInteger.Zero Then Return 1
        Return 0
    End Function
    Shared Operator =(x As BigRat, y As BigRat) As Boolean
        Return x.CompareTo(y) = 0
    End Operator
    Shared Operator <>(x As BigRat, y As BigRat) As Boolean
        Return x.CompareTo(y) <> 0
    End Operator
    Overrides Function ToString() As String
        If de = BigInteger.One Then Return nu.ToString
        Return String.Format("({0}/{1})", nu, de)
    End Function
    Shared Function Combine(a As BigRat, b As BigRat) As BigRat
        Return (a + b) / (BigRat.One - (a * b))
    End Function
End Class

Public Structure Term ' coefficent, BigRational construction for each term
    Dim c As Integer, br As BigRat
    Sub New(cc As Integer, bigr As BigRat)
        c = cc : br = bigr
    End Sub
End Structure

Module Module1
    Function Eval(c As Integer, x As BigRat) As BigRat
        If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)
        Dim hc As Integer = c \ 2
        Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))
    End Function

    Function Sum(terms As List(Of Term)) As BigRat
        If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)
        Dim htc As Integer = terms.Count / 2
        Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))
    End Function

    Function ParseLine(ByVal s As String) As List(Of Term)
        ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)
        While t.Contains(" ") : t = t.Replace(" ", "") : End While
        p = t.IndexOf("pi/4=") : If p < 0 Then _
            Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function
        t = t.Substring(p + 5)
        For Each item As String In t.Split(")")
            If item.Length > 5 Then
                If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse
                    item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then
                    Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item)
                    ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function
                End If
                x.c = 1 : x.br = New BigRat(BigRat.One)
                p = item.IndexOf("/") : If p > 0 Then
                    x.br.de = UInt64.Parse(item.Substring(p + 1))
                    item = item.Substring(0, p)
                    p = item.IndexOf("(") : If p > 0 Then
                        x.br.nu = UInt64.Parse(item.Substring(p + 1))
                        p = item.IndexOf("a") : If p > 0 Then
                            Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c)
                            If x.c = 0 Then x.c = 1
                            If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c
                        End If
                        ParseLine.Add(x)
                    End If
                End If
            End If
        Next
    End Function

    Sub Main(ByVal args As String())
        Dim nl As String = vbLf
        For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl &
              "pi/4 = 2Atan(1/3) + ATan(1/7)" & nl &
              "pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl &
              "pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl &
              "Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl &
              "pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl &
              "PI/4   = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl &
              "pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl &
              "pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl &
              "pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl &
              "pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl &
              "pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl &
              "pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393)  -    10  ATan( 1  /   11018 )" & nl &
              "pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 /  8149)" & nl &
              "pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl &
              "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl &
              "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl)
            Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item)
        Next
    End Sub
End Module


code ChOut=8, Text=12;  \intrinsic routines
int  Number(18);        \numbers from equations
def  LF=$0A;            \ASCII line feed (end-of-line character)

func Parse(S);          \Convert numbers in string S to binary in Number array
char S;
int  I, Neg;

        proc GetNum;    \Get number from string S
        int  N;
        [while S(0)<^0 ! S(0)>^9 do S:= S+1;
        N:= S(0)-^0;  S:= S+1;
        while S(0)>=^0 & S(0)<=^9 do
                [N:= N*10 + S(0) - ^0;  S:= S+1];
        Number(I):= N;  I:= I+1;
        ];

[while S(0)#^= do S:= S+1;      \skip to "="
I:= 0;
loop    [Neg:= false;           \assume positive term
        loop    [S:= S+1;       \next char
                case S(0) of
                  LF:   [Number(I):= 0;  return S+1];   \mark end of array
                  ^-:   Neg:= true;                     \term is negative
                  ^a:   [Number(I):= 1;  I:= I+1; quit] \no coefficient so use 1
                other if S(0)>=^0 & S(0)<=^9 then       \if digit
                        [S:= S-1;  GetNum;  quit];      \backup and get number
                ];
        GetNum;                                         \numerator
        if Neg then Number(I-1):= -Number(I-1);         \tan(-a) = -tan(a)
        GetNum;                                         \denominator
        ];
];

func GCD(U, V);         \Return the greatest common divisor of U and V
int  U, V;
int  T;
[while V do             \Euclid's method
    [T:= U;  U:= V;  V:= rem(T/V)];
return abs(U);
];

proc Verify;            \Verify that tangent of equation = 1 (i.e: E = F)
int  E, F, I, J;

    proc Machin(A, B, C, D);
    int  A, B, C, D;
    int  Div;
    \tan(a+b) = (tan(a) + tan(b)) / (1 - tan(a)*tan(b))
    \tan(arctan(A/B) + arctan(C/D))
    \   = (tan(arctan(A/B)) + tan(arctan(C/D))) / (1 - tan(arctan(A/B))*tan(arctan(C/D)))
    \   = (A/B + C/D) / (1 - A/B*C/D)
    \   = (A*D/B*D + B*C/B*D) / (B*D/B*D - A*C/B*D)
    \   = (A*D + B*C) / (B*D - A*C)
    [E:= A*D + B*C;  F:= B*D - A*C;
    Div:= GCD(E, F);    \keep integers from getting too big
    E:= E/Div;  F:= F/Div;
    ];

[E:= 0;  F:= 1;  I:= 0;
while Number(I) do
    [for J:= 1 to Number(I) do
        Machin(E, F, Number(I+1), Number(I+2));
    I:= I+3;
    ];
Text(0, if E=F then "Yes  " else "No   ");
];

char S, SS;  int I;
[S:= "pi/4 = arctan(1/2) + arctan(1/3)
pi/4 = 2*arctan(1/3) + arctan(1/7)
pi/4 = 4*arctan(1/5) - arctan(1/239)
pi/4 = 5*arctan(1/7) + 2*arctan(3/79)
pi/4 = 5*arctan(29/278) + 7*arctan(3/79)
pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)
pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)
pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)
pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)
pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)
pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)
pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)
pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)
pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)
pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)
pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)
 ";                             \Python version of equations (thanks!)
for I:= 1 to 17 do
        [SS:= S;                \save start of string line
        S:= Parse(S);           \returns start of next line
        Verify;                 \correct Machin equation? Yes or No
        repeat ChOut(0, SS(0)); SS:= SS+1 until SS(0)=LF;  ChOut(0, LF); \show equation
        ];
]


print(‘a’.code)       // prints "97"
print(Char(code' 97)) // prints "a"


*        Character codes EBCDIC    15/02/2017
CHARCODE CSECT
         USING  CHARCODE,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    prolog
         ST     R13,4(R15)         " <-
         ST     R15,8(R13)         " ->
         LR     R13,R15            " addressability
* Character to Decimal
         SR     R1,R1              r1=0
         IC     R1,=C'a'           insert character 'a'
         XDECO  R1,PG
         XPRNT  PG,L'PG            print -> 129
* Hexadecimal to character
         SR     R1,R1              r1=0
         IC     R1,=X'81'          insert character X'81'
         STC    R1,CHAR            store character r1
         XPRNT  CHAR,L'CHAR        print -> 'a'
* Decimal to character
         LH     R1,=H'129'         r1=129
         STC    R1,CHAR            store character r1
         XPRNT  CHAR,L'CHAR        print -> 'a'
*
         XDUMP  CHAR,L'CHAR        dump -> X'81'
*
RETURN   L      R13,4(0,R13)       epilog
         LM     R14,R12,12(R13)    " restore
         XR     R15,R15            " rc=0
         BR     R14                exit
PG       DS     CL12
CHAR     DS     CL1
         YREGS
         END    CHARCODE


        JSR ResetCoords					;RESET TYPING CURSOR

	MOVE.B #'A',D1
	MOVE.W #25,D2
	MOVE.B #0,(softCarriageReturn) ;new line takes the cursor to left edge of screen.
	jsr PrintAllTheCodes

	jsr ResetCoords
	MOVE.B #8,(Cursor_X)
	MOVE.B #'a',D1
	MOVE.W #25,D2
	MOVE.B #8,(softCarriageReturn)
	;set the writing cursor to column 3 of the screen
	;so we don't erase the old output.

	jsr PrintAllTheCodes

forever:
	bra forever

PrintAllTheCodes:
	MOVE.B D1,D0
	jsr PrintChar			;print the character as-is

	MOVE.B #" ",D0
	jsr PrintChar
	MOVE.B #"=",D0
	jsr PrintChar
	MOVE.B #" ",D0
	jsr PrintChar

	MOVE.B D1,D0			;get ready to print the code

	JSR UnpackNibbles8
	SWAP D0
	ADD.B #$30,D0
	JSR PrintChar

	SWAP D0
	CMP.B #10,D0
	BCS noCorrectHex
	ADD.B #$07,D0
noCorrectHex:
	ADD.B #$30,D0
	JSR PrintChar

	MOVE.B (softCarriageReturn),D0
	JSR doNewLine2				;new line, with D0 as the carraige return point.

	ADDQ.B #1,D1
	DBRA D2,PrintAllTheCodes
	rts

UnpackNibbles8:
; INPUT: D0 = THE VALUE YOU WISH TO UNPACK.
; HIGH NIBBLE IN HIGH WORD OF D0, LOW NIBBLE IN LOW WORD. SWAP D0 TO GET THE OTHER HALF.
	pushWord D1
		CLR.W D1
		MOVE.B D0,D1
		CLR.L D0
		MOVE.B D1,D0	 ;now D0 = D1 = $000000II, where I = input

		AND.B #$F0,D0	 ;chop off bottom nibble
		LSR.B #4,D0		 ;downshift top nibble into bottom nibble of the word
		SWAP D0			 ;store in high word
		AND.B #$0F,D1	 ;chop off bottom nibble
		MOVE.B D1,D0	 ;store in low word
	popWord D1
	rts


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program character64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessCodeChar:    .asciz "The code of character is : @ \n"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
sZoneconv:           .skip 32
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                          // entry of program

    mov x0,'A'
    ldr x1,qAdrsZoneconv
    bl conversion10S
    ldr x0,qAdrszMessCodeChar
    ldr x1,qAdrsZoneconv
    bl strInsertAtCharInc      // insert result at @ character
    bl affichageMess
    mov x0,'a'
    ldr x1,qAdrsZoneconv
    bl conversion10S
    ldr x0,qAdrszMessCodeChar
    ldr x1,qAdrsZoneconv
    bl strInsertAtCharInc     // insert result at @ character
    bl affichageMess
    mov x0,'1'
    ldr x1,qAdrsZoneconv
    bl conversion10S
    ldr x0,qAdrszMessCodeChar
    ldr x1,qAdrsZoneconv
    bl strInsertAtCharInc     // insert result at @ character
    bl affichageMess

100:                          // standard end of the program */
    mov x0,0                  // return code
    mov x8,EXIT               // request to exit program
    svc 0                     // perform the system call
qAdrsZoneconv:             .quad  sZoneconv
qAdrszMessCodeChar:        .quad szMessCodeChar
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


report zcharcode
data: c value 'A', n type i.
field-symbols <n> type x.

assign c to <n> casting.
move <n> to n.
write: c, '=', n left-justified.


(cw "~x0" (char-code #\a))
(cw "~x0" (code-char 97))


PROC Main()
  CHAR c=['a]
  BYTE b=[97]

  Put(c) Put('=) PrintBE(c)
  PrintB(b) Put('=) Put(b)
RETURN


trace(String.fromCharCode(97)); //prints 'a'
trace("a".charCodeAt(0));//prints '97'


with Ada.Text_IO;  use Ada.Text_IO;

procedure Char_Code is
begin
   Put_Line (Character'Val (97) & " =" & Integer'Image (Character'Pos ('a')));
end Char_Code;


# prints "97"
o_integer('a');
o_byte('\n');
# prints "a"
o_byte(97);
o_byte('\n');


main:(
  printf(($gl$, ABS "a")); # for ASCII this prints "+97" EBCDIC prints "+129" #
  printf(($gl$, REPR 97))  # for ASCII this prints "a"; EBCDIC prints "/" #
)


begin
    % display the character code of "a" (97 in ASCII)                        %
    write( decode( "a" ) );
    % display the character corresponding to 97 ("a" in ASCII)               %
    write( code( 97 ) );
end.


/* ARM assembly Raspberry PI  */
/*  program character.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
/* Initialized data */
.data
szMessCodeChar: .ascii "The code of character is :"
sZoneconv:		 .fill 12,1,' '
szCarriageReturn:  .asciz "\n"

/* UnInitialized data */
.bss

/*  code section */
.text
.global main
main:                /* entry of program  */
    push {fp,lr}    /* saves 2 registers */

    mov r0,#'A'
    ldr r1,iAdrsZoneconv
    bl conversion10S
    ldr r0,iAdrszMessCodeChar
    bl affichageMess
    mov r0,#'a'
    ldr r1,iAdrsZoneconv
    bl conversion10S
    ldr r0,iAdrszMessCodeChar
    bl affichageMess
    mov r0,#'1'
    ldr r1,iAdrsZoneconv
    bl conversion10S
    ldr r0,iAdrszMessCodeChar
    bl affichageMess

100:   /* standard end of the program */
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call
iAdrsZoneconv:		.int  sZoneconv
iAdrszMessCodeChar:		.int szMessCodeChar
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save  registres */
    push {r0,r1,r2,r7}    		/* save others registers */
    mov r2,#0   				/* counter length */
1:      	/* loop length calculation */
    ldrb r1,[r0,r2]  			/* read octet start position + index */
    cmp r1,#0       			/* if 0 its over */
    addne r2,r2,#1   			/* else add 1 in the length */
    bne 1b          			/* and loop */
                                /* so here r2 contains the length of the message */
    mov r1,r0        			/* address message in r1 */
    mov r0,#STDOUT      		/* code to write to the standard output Linux */
    mov r7, #WRITE             /* code call system "write" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7}     		/* restaur others registers */
    pop {fp,lr}    				/* restaur des  2 registres */
    bx lr	        			/* return  */

/***************************************************/
/*   conversion register signed décimal     */
/***************************************************/
/* r0 contient le registre   */
/* r1 contient l adresse de la zone de conversion */
conversion10S:
    push {r0-r5,lr}    /* save des registres */
    mov r2,r1       /* debut zone stockage */
    mov r5,#'+'     /* par defaut le signe est + */
    cmp r0,#0       /* nombre négatif ? */
    movlt r5,#'-'     /* oui le signe est - */
    mvnlt r0,r0       /* et inversion en valeur positive */
    addlt r0,#1
    mov r4,#10   /* longueur de la zone */
1: /* debut de boucle de conversion */
    bl divisionpar10 /* division  */
    add r1,#48        /* ajout de 48 au reste pour conversion ascii */
    strb r1,[r2,r4]  /* stockage du byte en début de zone r5 + la position r4 */
    sub r4,r4,#1      /* position précedente */
    cmp r0,#0
    bne 1b	       /* boucle si quotient different de zéro */
    strb r5,[r2,r4]  /* stockage du signe à la position courante */
    subs r4,r4,#1   /* position précedente */
    blt  100f         /* si r4 < 0  fin  */
    /* sinon il faut completer le debut de la zone avec des blancs */
    mov r3,#' '   /* caractere espace */
2:
    strb r3,[r2,r4]  /* stockage du byte  */
    subs r4,r4,#1   /* position précedente */
    bge 2b        /* boucle si r4 plus grand ou egal a zero */
100:  /* fin standard de la fonction  */
    pop {r0-r5,lr}   /*restaur desregistres */
    bx lr

/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 contient le dividende   */
/* r0 retourne le quotient */
/* r1 retourne le reste  */
divisionpar10:
  /* r0 contains the argument to be divided by 10 */
   push {r2-r4}   /* save registers  */
   mov r4,r0
   ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
   smull r1, r2, r3, r0   /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
   mov r2, r2, ASR #2     /* r2 <- r2 >> 2 */
   mov r1, r0, LSR #31    /* r1 <- r0 >> 31 */
   add r0, r2, r1         /* r0 <- r2 + r1 */
   add r2,r0,r0, lsl #2   /* r2 <- r0 * 5 */
   sub r1,r4,r2, lsl #1   /* r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10) */
   pop {r2-r4}
   bx lr                  /* leave function */
   bx lr                  /* leave function */
.Ls_magic_number_10: .word 0x66666667


CATALAN  CSECT
         USING  CATALAN,R13,R12
SAVEAREA B      STM-SAVEAREA(R15)
         DC     17F'0'
         DC     CL8'CATALAN'
STM      STM    R14,R12,12(R13)
         ST     R13,4(R15)
         ST     R15,8(R13)
         LR     R13,R15
         LA     R12,4095(R13)
         LA     R12,1(R12)
*        ----   CODE
         LA     R0,1
         ST     R0,T            t(1)=1
         LA     R4,0            ix:i=1
         LA     R6,1            by 1
         LH     R7,N            to n
LOOPI    BXH    R4,R6,ENDLOOPI  loop i
         LR     R5,R4           ix:j=i+1
         LA     R5,2(R5)        i+2
         LA     R8,0
         BCTR   R8,0            by -1
         LA     R9,1            to 2
LOOP1J   BXLE   R5,R8,ENLOOP1J  loop j
         LR     R10,R5          j
         BCTR   R10,0
         SLA    R10,2
         L      R2,T(R10)       r2=t(j)
         LR     R1,R10          j
         SH     R1,=H'4'
         L      R3,T(R1)        r3=t(j-1)
         AR     R2,R3           r2=r2+r3
         ST     R2,T(R10)       t(j)=t(j)+t(j-1)
         B      LOOP1J
ENLOOP1J EQU    *
         LR     R1,R4           i
         BCTR   R1,0
         SLA    R1,2
         L      R3,T(R1)        t(i)
         LA     R1,4(R1)
         ST     R3,T(R1)        t(i+1)
         LR     R5,R4           ix:j=i+2
         LA     R5,3(R5)        i+3
         LA     R8,0
         BCTR   R8,0            by -1
         LA     R9,1            to 2
LOOP2J   BXLE   R5,R8,ENLOOP2J  loop j
         LR     R10,R5          j
         BCTR   R10,0
         SLA    R10,2
         L      R2,T(R10)       r2=t(j)
         LR     R1,R10          j
         SH     R1,=H'4'
         L      R3,T(R1)        r3=t(j-1)
         AR     R2,R3           r2=r2+r3
         ST     R2,T(R10)       t(j)=t(j)+t(j-1)
         B      LOOP2J
ENLOOP2J EQU    *
         LR     R1,R4           i
         BCTR   R1,0
         SLA    R1,2
         L      R2,T(R1)        t(i)
         LA     R1,4(R1)
         L      R3,T(R1)        t(i+1)
         SR     R3,R2
         CVD    R3,P
         UNPK   Z,P
         MVC    C,Z
         OI     C+L'C-1,X'F0'
         MVC    WTOBUF(8),C+8
         WTO    MF=(E,WTOMSG)
         B      LOOPI
ENDLOOPI EQU    *
*        ----   END CODE
         CNOP   0,4
         L      R13,4(0,R13)
         LM     R14,R12,12(R13)
         XR     R15,R15
         BR     R14
*        ----   DATA
N        DC     H'15'
T        DC     17F'0'
P        DS     PL8
Z        DS     ZL16
C        DS     CL16
WTOMSG   DS     0F
         DC     H'80'
         DC     H'0'
WTOBUF   DC     CL80' '
         YREGS
         END


INCLUDE "D2:REAL.ACT" ;from the Action! Tool Ki

DEFINE PTR="CARD"
DEFINE REALSIZE="6"

PTR FUNC GetItemAddr(PTR buf BYTE i)
RETURN (buf+REALSIZE*i)

PROC Main()
  DEFINE COUNT="15"
  BYTE ARRAY buf(102) ;(COUNT+2)*REALSIZE
  REAL POINTER r1,r2
  REAL c
  BYTE i,j

  Put(125) PutE() ;clear the screen

  r1=GetItemAddr(buf,1)
  IntToReal(1,r1)

  FOR i=1 TO COUNT
  DO
    j=i+1
    WHILE j>=2
    DO
      r1=GetItemAddr(buf,j)
      r2=GetItemAddr(buf,j-1)
      RealAdd(r1,r2,r1) ;t(j)==+t(j-1)
      j==-1
    OD
    r1=GetItemAddr(buf,i)
    r2=GetItemAddr(buf,i+1)
    RealAssign(r1,r2) ;t(i+1)=t(i)

    j=i+2
    WHILE j>=2
    DO
      r1=GetItemAddr(buf,j)
      r2=GetItemAddr(buf,j-1)
      RealAdd(r1,r2,r1) ;t(j)==+t(j-1)
      j==-1
    OD
    r1=GetItemAddr(buf,i)
    r2=GetItemAddr(buf,i+1)
    RealSub(r2,r1,c) ;c=t(i+1)-t(i)
    PrintF("C(%B)=",i) PrintRE(c)
  OD
RETURN


with Ada.Text_IO, Pascal;

procedure Catalan is

   Last: Positive := 15;
   Row: Pascal.Row := Pascal.First_Row(2*Last+1);

begin
   for I in 1 .. Last loop
      Row := Pascal.Next_Row(Row);
      Row := Pascal.Next_Row(Row);
      Ada.Text_IO.Put(Integer'Image(Row(I+1)-Row(I+2)));
   end loop;
end Catalan;


INT n = 15;
[ 0 : n + 1 ]INT t;
t[0] := 0;
t[1] := 1;
FOR i TO n DO
    FOR j FROM i   BY -1 TO 2 DO t[j] := t[j] + t[j-1] OD;
    t[i+1] := t[i];
    FOR j FROM i+1 BY -1 TO 2 DO t[j] := t[j] + t[j-1] OD;
    print( ( whole( t[i+1] - t[i], 0 ), " " ) )
OD


print to :integer first "a"
print to :integer `a`
print to :char 97


function ord(c)
{
  return chmap[c]
}
BEGIN {
  for(i=0; i < 256; i++) {
    chmap[sprintf("%c", i)] = i
  }
  print ord("a"), ord("b")
  printf "%c %c\n", 97, 98
  s = sprintf("%c%c", 97, 98)
  print s
}


begin
    % print the first 15 Catalan numbers from Pascal's triangle %
    integer n;
    n := 15;
    begin
        integer array pascalLine ( 1 :: n + 1 );
        % the Catalan numbers are the differences between the middle and middle - 1 numbers of the odd %
        % lines of Pascal's triangle (lines with 3 or more numbers)                                    %
        % note - we only need to calculate the left side of the triangle                               %
        pascalLine( 1 ) := 1;
        for c := 2 until n + 1 do begin
            % even line %
            for i := c - 1 step -1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i );
            pascalLine( c ) := pascalLine( c - 1 );
            % odd line %
            for i := c     step -1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i );
            writeon( i_w := 1, s_w := 0, " ", pascalLine( c ) - pascalLine( c - 1 ) )
        end for_c
    end
end.


      ⍝ Based heavily on the J solution
      CATALAN←{¯1↓↑-/1 ¯1↓¨(⊂⎕IO+0 0)⍉¨0 2⌽¨⊂(⎕IO-⍨⍳N){+\⍣⍺⊢⍵}⍤0 1⊢1⍴⍨N←⍵+2}


/* Generate Catalan Numbers
//
// smgs: 20th Feb, 2014
*/
Array := [], Array[2,1] := Array[2,2] := 1 ; Array inititated and 2nd row of pascal's triangle assigned
INI := 3 ; starts with calculating the 3rd row and as such the value
Loop, 31 ; every odd row is taken for calculating catalan number as such to obtain 15 we need 2n+1
{
	if ( A_index > 2 )
	{
		Loop, % A_INDEX
		{
			old := ini-1, 		index := A_index, 		index_1 := A_index + 1
			Array[ini, index_1] := Array[old, index] + Array[old, index_1]
			Array[ini, 1] := Array[ini, ini] := 1
			line .= Array[ini, A_index] " "
		}
	;~ MsgBox % line ; gives rows of pascal's triangle
	; calculating every odd row starting from 1st so as to obtain catalan's numbers
		if ( mod(ini,2) != 0)
		{
			StringSplit, res, line, %A_Space%
			ans := res0//2, ans_1 := ans++
			result := result . res%ans_1% - res%ans% " "
		}
	line :=
	ini++
	}
}
MsgBox % result


charCode = 97
char = "a"
PRINT CHR$(charCode) 'prints a
PRINT ASC(char) 'prints 97


# syntax: GAWK -f CATALAN_NUMBERS_PASCALS_TRIANGLE.AWK
# converted from C
BEGIN {
    printf("1")
    for (n=2; n<=15; n++) {
      num = den = 1
      for (k=2; k<=n; k++) {
        num *= (n + k)
        den *= k
        catalan = num / den
      }
      printf(" %d",catalan)
    }
    printf("\n")
    exit(0)
}


@echo off
setlocal ENABLEDELAYEDEXPANSION
set n=15
set /A nn=n+1
for /L %%i in (0,1,%nn%) do set t.%%i=0
set t.1=1
for /L %%i in (1,1,%n%) do (
    set /A ip=%%i+1
    for /L %%j in (%%i,-1,1) do (
        set /A jm=%%j-1
	    set /A t.%%j=t.%%j+t.!jm!
	)
    set /A t.!ip!=t.%%i
    for /L %%j in (!ip!,-1,1) do (
        set /A jm=%%j-1
	    set /A t.%%j=t.%%j+t.!jm!
	)
    set /A ci=t.!ip!-t.%%i
	echo !ci!
  )
)
pause


//This code implements the print of 15 first Catalan's Numbers
//Formula used:
//  __n__
//   | |  (n + k) / k  n>0
//   k=2

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

//the number of Catalan's Numbers to be printed
const int N = 15;

int main()
{
    //loop variables (in registers)
    register int k, n;

    //necessarily ull for reach big values
    unsigned long long int num, den;

    //the nmmber
    int catalan;

    //the first is not calculated for the formula
    printf("1 ");

    //iterating from 2 to 15
    for (n=2; n<=N; ++n) {
        //initializaing for products
        num = den = 1;
        //applying the formula
        for (k=2; k<=n; ++k) {
            num *= (n+k);
            den *= k;
            catalan = num /den;
        }

        //output
        printf("%d ", catalan);
    }

    //the end
    printf("\n");
    return 0;
}


# ASCII char
charCode = 97
char$ = "a"
print chr(97)	#prints a
print asc("a")  #prints 97

# Unicode char
charCode = 960
char$ = "π"
print chr(960)  #prints π
print asc("π")  #prints 960


@echo off

:: Supports all ASCII characters and codes from 34-126 with the exceptions of:
:: 38  &
:: 60  <
:: 62  >
:: 94  ^
:: 124 |

:_main
call:_toCode a
call:_toChar 97
pause>nul
exit /b

:_toCode
setlocal enabledelayedexpansion
set codecount=32

for /l %%i in (33,1,126) do (
  set /a codecount+=1
  cmd /c exit %%i
  if %1==!=exitcodeAscii! (
    echo !codecount!
    exit /b
  )
)

:_toChar
setlocal
cmd /c exit %1
echo %=exitcodeAscii%
exit /b


      charCode = 97
      char$ = "a"
      PRINT CHR$(charCode) : REM prints a
      PRINT ASC(char$) : REM prints 97


// Generate Catalan Numbers
//
// Nigel Galloway: June 9th., 2012
//
#include <iostream>
int main() {
  const int N = 15;
  int t[N+2] = {0,1};
  for(int i = 1; i<=N; i++){
    for(int j = i; j>1; j--) t[j] = t[j] + t[j-1];
    t[i+1] = t[i];
    for(int j = i+1; j>1; j--) t[j] = t[j] + t[j-1];
    std::cout << t[i+1] - t[i] << " ";
  }
  return 0;
}


   FromCharCode ← @⊸+
@⊸+
   FromCharCode 97
'a'
   FromCharCode 97‿67‿126
"aC~"
   FromCharCode⁼ 'a'
97


#include <stdio.h>

int main() {
  printf("%d\n", 'a'); /* prints "97" */
  printf("%c\n", 97); /* prints "a"; we don't have to cast because printf is type agnostic */
  return 0;
}


(defun catalan (n)
  "Return the n-th Catalan number"
  (if (<= n 1)  1
    (let ((result 2))
      (dotimes (k (- n 2) result)
        (setq result (* result (/ (+ n k 2) (+ k 2)))) ))))

(dotimes (n 15)
  (print (catalan (1+ n))) )


void main() {
    import std.stdio;

    enum uint N = 15;
    uint[N + 2] t;
    t[1] = 1;

    foreach (immutable i; 1 .. N + 1) {
        foreach_reverse (immutable j; 2 .. i + 1)
            t[j] += t[j - 1];
        t[i + 1] = t[i];
        foreach_reverse (immutable j; 2 .. i + 2)
            t[j] += t[j - 1];
        write(t[i + 1] - t[i], ' ');
    }
}


using System;

namespace RosettaCode.CharacterCode
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine((int) 'a');   //Prints "97"
            Console.WriteLine((char) 97);   //Prints "a"
        }
    }
}


#include <iostream>

int main() {
  std::cout << (int)'a' << std::endl; // prints "97"
  std::cout << (char)97 << std::endl; // prints "a"
  return 0;
}


(print (int \a)) ; prints "97"
(print (char 97)) ; prints \a

; Unicode is also available, as Clojure uses the underlying java Strings & chars
(print (int \π))  ; prints 960
(print (char 960)) ; prints \π

; use String because char in Java can't represent characters outside Basic Multilingual Plane
(print (.codePointAt "𝅘𝅥𝅮" 0)) ; prints 119136
(print (String. (int-array 1 119136) 0 1)) ; prints 𝅘𝅥𝅮


(define dim 100)
(define-syntax-rule  (Tidx i j)  (+ i (* dim j)))

;; generates Catalan's triangle
;; T (i , j) = T(i-1,j) + T (i, j-1)

(define (T n)
	(define i (modulo n dim))
	(define j (quotient n dim))
	(cond
		((zero? i) 1) ;; left column = 1
		((= i j) (T (Tidx (1- i) j))) ;; diagonal value = left value
		(else (+ (T (Tidx (1- i) j)) (T (Tidx i (1- j)))))))

(remember 'T #(1))


start_up = proc ()
    po: stream := stream$primary_output()

    % To turn a character code into an integer, use char$c2i
    % (but then to print it, it needs to be turned into a string first
    % with int$unparse)
    stream$putl(po, int$unparse( char$c2i( 'a' ) ) ) % prints '97'

    % To turn an integer into a character code, use char$i2c
    stream$putc(po, char$i2c( 97 ) );  % prints 'a'
end start_up


       identification division.
       program-id. character-codes.
       remarks. COBOL is an ordinal language, first is 1.
       remarks. 42nd ASCII code is ")" not, "*".
       procedure division.
       display function char(42)
       display function ord('*')
       goback.
       end program character-codes.


console.log 'a'.charCodeAt 0 # 97
console.log String.fromCharCode 97 # a


 [Catalan numbers from Pascal triangle, Rosetta Code website.
  EDSAC program, Initial Orders 2]
            ..PZ  [blank tape and terminator]
            T54K  [refer to working array with 'C']
            P300F [address of working array]
            T46K  [to call print subroutine with 'G N']
            P56F  [address of print subroutine]

 [Modification of library subroutine P7.
  Prints non-negative integer, up to 10 digits, right-justified.
  55 locations, load at even address.]
           E25KTN
  [email protected]@[email protected]@[email protected]@[email protected]#@[email protected]
  [email protected]@[email protected]@[email protected]@[email protected]
  [email protected]@[email protected]@[email protected]@[email protected]@

 [Main program]
            PK  T200K GK
        [Constants]
      [0]   PD   [short constant 1]
      [1]   P2F  [to inc address by 2]
      [2]   T#C  [used in manufacturing EDSAC orders]
      [3]   MF   [add to T order to make A order with same address]
      [4]   #F   [set figures]
      [5]   &F   [line feed]
      [6]   @F   [carriage return]
      [7]   P7D  [maximum n = 15]
        [Variable]
      [8]   PF   [n]
        [Enter with acc = 0]
      [9]   [email protected]                      [set teleprinter to figures]
            T4#C  T2#C  T#C  [email protected]  TC  [initialize first 3 terms to 1, 0, 0]
            [email protected]  [email protected]                [set n := 0; jump to inc n and print C_n]
        [Outer loop; here with n updated]
     [17]   TF  [email protected]                  [acc := latest n]
            L1F  [email protected]  [email protected]           [make and store order 'T 2n #C']
     [22]   T#C                      [sets term := 0; also used to test for end of loop]
            [email protected]                      [load 'T#C', initial value of order 31]
        [Loop to convert e.g. (20, 15, 6, 1) to (35, 21, 7, 1); works left to right]
     [24]   [email protected]  [email protected]  [email protected]  [email protected]  [email protected]  [set up orders on next line]
     [29]   A#C  A#C  T#C            [replaced by manufactured orders]
            [email protected]  [email protected]  [email protected]  [email protected]    [inc address in order 31, jump out if done]
            [email protected]  [email protected]               [not done, loop back]
     [38]   [email protected]  [email protected]               [initialize order 48]
        [Loop to convert e.g. (35, 21, 7, 1) to (70, 56, 28, 8, 1); works right to left]
     [40]   TF [email protected]  [email protected]  [email protected]  [email protected]  [email protected]  [set up orders on next line]
     [46]   A#C  A#C  T#C            [replaced by manufactured orders]
            [email protected]  [email protected]  [email protected]          [dec address in order 48]
            [email protected]  [email protected]  [email protected]          [test for done, loop back if not]
            A#C  LD  T#C             [double first term, e.g. 35 -> 70 (not done in loop)]
        [Increment n and print Catalan number C_n]
     [58]   TD                       [clear 0D, ensures sandwich bit = 0]
            [email protected]  [email protected]  [email protected]  TF         [inc n; set 0D := n by setting 0F := n]
            [email protected]  GN                 [print n]
            A#C  S4#C  TD  [email protected]  GN  [print Catalan number C_n, e.g. C_5 = 70 - 28 = 42]
            [email protected]  [email protected]                 [print CR, LF]
            [email protected]  [email protected]  [email protected]           [test for maximum n, loop back if not]
     [75]   [email protected]  ZF                  [flush printer buffer; stop]
            E9Z  PF                  [define entry point; enter with acc = 0]


defmodule Catalan do
  def numbers(num) do
    {result,_} = Enum.reduce(1..num, {[],{0,1}}, fn i,{list,t0} ->
      t1 = numbers(i, t0)
      t2 = numbers(i+1, Tuple.insert_at(t1, i+1, elem(t1, i)))
      {[elem(t2, i+1) - elem(t2, i) | list], t2}
    end)
    Enum.reverse(result)
  end

  defp numbers(0, t), do: t
  defp numbers(n, t), do: numbers(n-1, put_elem(t, n, elem(t, n-1) + elem(t, n)))
end

IO.inspect Catalan.numbers(15)


-module(catalin).
-compile(export_all).
mul(N,D,S,S)->
	N2=N*(S+S),
	D2=D*S,
	K = N2 div D2 ;
mul(N,D,S,L)->
	N2=N*(S+L),
	D2=D*L,
	K = mul(N2,D2,S,L+1).

catl(Ans,16) -> Ans;
catl(D,S)->
	C=mul(1,1,S,2),
	catl([D|C],S+1).
main()->
	Ans=catl(1,2).


(princ (char-code #\a)) ; prints "97"
(princ (code-char 97)) ; prints "a"


PROCEDURE CharCodes*;
VAR
	c : CHAR;
BEGIN
	c := 'A';
	StdLog.Char(c);StdLog.String(":> ");StdLog.Int(ORD(c));StdLog.Ln;
	c := CHR(3A9H);
	StdLog.Char(c);StdLog.String(":> ");StdLog.Int(ORD(c));StdLog.Ln
END CharCodes;


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

    string test = "a";
    size_t index = 0;

    // Get four-byte utf32 value for index 0.
    writefln("%d", test.decode(index));

    // 'index' has moved to next character input position.
    assert(index == 1);
}


PROGRAM CATALAN

!$DOUBLE

DIM CATALAN[50]

FUNCTION ODD(X)
    ODD=FRC(X/2)<>0
END FUNCTION

PROCEDURE GETCATALAN(L)
    LOCAL J,K,W
    LOCAL DIM PASTRI[100]

    L=L*2
    PASTRI[0]=1
    J=0
    WHILE J<L DO
       J+=1
       K=INT((J+1)/2)
       PASTRI[K]=PASTRI[K-1]
       FOR W=K TO 1 STEP -1 DO
          PASTRI[W]+=PASTRI[W-1]
       END FOR
       IF NOT(ODD(J)) THEN
          K=INT(J/2)
          CATALAN[K]=PASTRI[K]-PASTRI[K-1]
       END IF
    END WHILE
END PROCEDURE

BEGIN
   LL=15
   GETCATALAN(LL)
   FOR I=1 TO LL DO
      WRITE("### ####################";I;CATALAN[I])
   END FOR
END PROGRAM


let mutable nm=uint64(1)
let mutable dm=uint64(1)
let mutable a=uint64(1)

printf "1, "
for i = 2 to 15 do
    nm<-uint64(1)
    dm<-uint64(1)
    for k = 2 to i do
        nm <-uint64( uint64(nm) * (uint64(i)+uint64(k)))
        dm <-uint64( uint64(dm) * uint64(k))
    let a = uint64(uint64(nm)/uint64(dm))
    printf "%u"a
    if(i<>15) then
        printf ", "


USING: arrays grouping io kernel math prettyprint sequences ;
IN: rosetta-code.catalan-pascal

: next-row ( seq -- seq' )
    2 clump [ sum ] map 1 prefix 1 suffix ;

: pascal ( n -- seq )
    1 - { { 1 } } swap [ dup last next-row suffix ] times ;

15 2 * pascal [ length odd? ] filter [
    dup length 1 = [ 1 ]
    [ dup [email protected] dup 1 + 2array swap nths first2 - ] if
    pprint bl
] each drop


program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils;
var
  aChar:Char;
  aCode:Byte;
  uChar:WideChar;
  uCode:Word;
begin
  aChar := Chr(97);       Writeln(aChar);
  aCode := Ord(aChar);    Writeln(aCode);
  uChar := WideChar(97);  Writeln(uChar);
  uCode := Ord(uChar);    Writeln(uCode);

  Readln;
end.


' version 15-09-2015
' compile with: fbc -s console

#Define size 31                 ' (N * 2 + 1)

Sub pascal_triangle(rows As Integer, Pas_tri() As ULongInt)

    Dim As Integer x, y

    For x = 1 To rows
        Pas_tri(1,x) = 1
        Pas_tri(x,1) = 1
    Next

    For x = 2 To rows
        For y = 2 To rows + 1 - x
            Pas_tri(x, y) = pas_tri(x - 1 , y) + pas_tri(x, y - 1)
        Next
    Next

End Sub

' ------=< MAIN >=------

Dim As Integer count, row
Dim As ULongInt triangle(1 To size, 1 To size)

pascal_triangle(size, triangle())

'  1   1   1   1   1   1
'  1   2   3   4   5   6
'  1   3   6  10  15  21
'  1   4  10  20  35  56
'  1   5  15  35  70 126
'  1   6  21  56 126 252
' The Pascal triangle is rotated 45 deg.
' to find the Catalan number we need to follow the diagonal
' for top left to bottom right
' take the number on diagonal and subtract the number in de cell
' one up and one to right
' 1 (2 - 1), 2 (6 - 4), 5 (20 - 15) ...

Print "The first 15 Catalan numbers are" : print
count = 1 : row = 2
Do
    Print Using "###: #########"; count; triangle(row, row) - triangle(row +1, row -1)
    row = row + 1
    count =  count + 1
Loop Until count > 15

' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


? 'a'.asInteger()
# value: 97

? <import:java.lang.makeCharacter>.asChar(97)
# value: 'a'


class
	APPLICATION
inherit
	ARGUMENTS
create
	make

feature {NONE} -- Initialization

	make
			-- Run application.
		local
			c8: CHARACTER_8
			c32: CHARACTER_32
		do
			c8 := '%/97/'			-- using code value notation
			c8 := '%/0x61/'			-- same as above, but using hexadecimal literal
			print(c8.natural_32_code)	-- prints "97"
			print(c8)			-- prints the character "a"

			c32 := 'a'			-- using character literal
			print(c32.natural_32_code)	-- prints "97"
			print(c32)			-- prints "U+00000061"

			--c8 := 'π'			-- compile-time error (c8 does not have enough range)
			c32 := 'π'			-- assigns Unicode value 960
		end
end


class Catalan
{
 public static void main(String[] args)
  {
    BigInteger N = 15;
    BigInteger k,n,num,den;
    BigInteger  catalan;
      print(1);
       for(n=2;n<=N;n++)
          {
            num = 1;
            den = 1;
              for(k=2;k<=n;k++)
                 {
                    num = num*(n+k);
                    den = den*k;
                    catalan = num/den;
                 }
            print(" " + catalan);
          }

  }
}


import System.Environment (getArgs)

-- Pascal's triangle.
pascal :: [[Integer]]
pascal = [1] : map (\row -> 1 : zipWith (+) row (tail row) ++ [1]) pascal

-- The Catalan numbers from Pascal's triangle.  This uses a method from
-- http://www.cut-the-knot.org/arithmetic/algebra/CatalanInPascal.shtml
-- (see "Grimaldi").
catalan :: [Integer]
catalan = map (diff . uncurry drop) $ zip [0..] (alt pascal)
  where alt (x:_:zs) = x : alt zs -- every other element of an infinite list
        diff (x:y:_) = x - y
        diff (x:_)   = x

main :: IO ()
main = do
  ns <- fmap (map read) getArgs :: IO [Int]
  mapM_ (print . flip take catalan) ns


import extensions;

public program()
{
    var ch := $97;

    console.printLine:ch;
    console.printLine(ch.toInt())
}


iex(1)> code = ?a
97
iex(2)> to_string([code])
"a"