use std::cmp;

fn lcs(string1: String, string2: String) -> (usize, String){
    let total_rows = string1.len() + 1;
    let total_columns = string2.len() + 1;
    // rust doesn't allow accessing string by index
    let string1_chars = string1.as_bytes();
    let string2_chars = string2.as_bytes();

    let mut table = vec![vec![0; total_columns]; total_rows];

    for row in 1..total_rows{
        for col in 1..total_columns {
            if string1_chars[row - 1] == string2_chars[col - 1]{
                table[row][col] = table[row - 1][col - 1] + 1;
            } else {
                table[row][col] = cmp::max(table[row][col-1], table[row-1][col]);
            }
        }
    }

    let mut common_seq = Vec::new();
    let mut x = total_rows - 1;
    let mut y = total_columns - 1;

    while x != 0 && y != 0 {
        // Check element above is equal
        if table[x][y] == table[x - 1][y] {
            x = x - 1;
        }
        // check element to the left is equal
        else if table[x][y] == table[x][y - 1] {
            y = y - 1;
        }
        else {
            // check the two element at the respective x,y position is same
            assert_eq!(string1_chars[x-1], string2_chars[y-1]);
            let char = string1_chars[x - 1];
            common_seq.push(char);
            x = x - 1;
            y = y - 1;
        }
    }
    common_seq.reverse();
    (table[total_rows - 1][total_columns - 1], String::from_utf8(common_seq).unwrap())
}

fn main() {
    let res = lcs("abcdaf".to_string(), "acbcf".to_string());
    assert_eq!((4 as usize, "abcf".to_string()), res);
    let res = lcs("thisisatest".to_string(), "testing123testing".to_string());
    assert_eq!((7 as usize, "tsitest".to_string()), res);
    // LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
    let res = lcs("AGGTAB".to_string(), "GXTXAYB".to_string());
    assert_eq!((4 as usize, "GTAB".to_string()), res);
}


  def lcsLazy[T](u: IndexedSeq[T], v: IndexedSeq[T]): IndexedSeq[T] = {
    def su = subsets(u).to(LazyList)
    def sv = subsets(v).to(LazyList)
    su.intersect(sv).headOption match{
      case Some(sub) => sub
      case None => IndexedSeq[T]()
    }
  }

  def subsets[T](u: IndexedSeq[T]): Iterator[IndexedSeq[T]] = {
    u.indices.reverseIterator.flatMap{n => u.indices.combinations(n + 1).map(_.map(u))}
  }


;; using srfi-69
(define (memoize proc)
  (let ((results (make-hash-table)))
    (lambda args
      (or (hash-table-ref results args (lambda () #f))
          (let ((r (apply proc args)))
            (hash-table-set! results args r)
            r)))))

(define (longest xs ys)
  (if (> (length xs)
         (length ys))
      xs ys))

(define lcs
  (memoize
   (lambda (seqx seqy)
     (if (pair? seqx)
         (let ((x (car seqx))
               (xs (cdr seqx)))
           (if (pair? seqy)
               (let ((y (car seqy))
                     (ys (cdr seqy)))
                 (if (equal? x y)
                     (cons x (lcs xs ys))
                     (longest (lcs seqx ys)
                              (lcs xs seqy))))
               '()))
         '()))))


$ include "seed7_05.s7i";

const func string: lcs (in string: a, in string: b) is func
  result
    var string: lcs is "";
  local
    var string: x is "";
    var string: y is "";
  begin
    if a <> "" and b <> "" then
      if a[length(a)] = b[length(b)] then
        lcs := lcs(a[.. pred(length(a))], b[.. pred(length(b))]) & str(a[length(a)]);
      else
        x := lcs(a, b[.. pred(length(b))]);
        y := lcs(a[.. pred(length(a))], b);
        if length(x) > length(y) then
          lcs := x;
        else
          lcs := y;
        end if;
      end if;
    end if;
  end func;

const proc: main is func
  begin
    writeln(lcs("thisisatest", "testing123testing"));
    writeln(lcs("1234", "1224533324"));
  end func;


import <Utilities/Sequence.sl>;

lcsBack(a(1), b(1)) :=
    let
        aSub := allButLast(a);
        bSub := allButLast(b);

        x := lcsBack(a, bSub);
        y := lcsBack(aSub, b);
    in
        [] when size(a) = 0 or size(b) = 0
    else
        lcsBack(aSub, bSub) ++ [last(a)] when last(a) = last(b)
    else
        x when size(x) > size(y)
    else
        y;

main(args(2)) :=
        lcsBack(args[1], args[2]) when size(args) >=2
    else
        lcsBack("thisisatest", "testing123testing");


    op .longest(a, b);
      return if #a > #b then a else b end;
    end .longest;

    procedure lcs(a, b);
      if exists empty in {a, b} | #empty = 0 then
        return empty;
      elseif a(1) = b(1) then
        return a(1) + lcs(a(2..), b(2..));
      else
        return lcs(a(2..), b) .longest lcs(a, b(2..));
      end;
    end lcs;


func lcs(xstr, ystr) is cached {

    xstr.is_empty && return xstr;
    ystr.is_empty && return ystr;

    var(x, xs, y, ys) = (xstr.ft(0,0), xstr.ft(1),
                         ystr.ft(0,0), ystr.ft(1));

    if (x == y) {
        x + lcs(xs, ys)
    } else {
        [lcs(xstr, ys), lcs(xs, ystr)].max_by { .len };
    }
}

say lcs("thisisatest", "testing123testing");


[email protected](Sequence traits) longestCommonSubsequenceWith: [email protected](Sequence traits)
[
  s1 isEmpty \/ s2 isEmpty ifTrue: [^ {}].
  s1 last = s2 last
    ifTrue: [(s1 allButLast longestCommonSubsequenceWith: s2 allButLast) copyWith: s1 last]
    ifFalse: [| x y |
              x: (s1 longestCommonSubsequenceWith: s2 allButLast).
              y: (s1 allButLast longestCommonSubsequenceWith: s2).
              x length > y length ifTrue: [x] ifFalse: [y]]
].


rlcs(_ s1: String, _ s2: String) -> String {
   if s1.count == 0 || s2.count == 0 {
       return ""
   } else if s1[s1.index(s1.endIndex, offsetBy: -1)] == s2[s2.index(s2.endIndex, offsetBy: -1)] {
       return rlcs(String(s1[s1.startIndex..<s1.index(s1.endIndex, offsetBy: -1)]),
                   String(s2[s2.startIndex..<s2.index(s2.endIndex, offsetBy: -1)])) + String(s1[s1.index(s1.endIndex, offsetBy: -1)])
   } else {
       let str1 = rlcs(s1, String(s2[s2.startIndex..<s2.index(s2.endIndex, offsetBy: -1)]))
       let str2 = rlcs(String(s1[s1.startIndex..<s1.index(s1.endIndex, offsetBy: -1)]), s2)

       return str1.count > str2.count ? str1 : str2
   }
}


proc r_lcs {a b} {
    if {$a eq "" || $b eq ""} {return ""}
    set a_ [string range $a 1 end]
    set b_ [string range $b 1 end]
    if {[set c [string index $a 0]] eq [string index $b 0]} {
        return "$c[r_lcs $a_ $b_]"
    } else {
        set x [r_lcs $a $b_]
        set y [r_lcs $a_ $b]
        return [expr {[string length $x] > [string length $y] ? $x :$y}]
    }
}


#import std

lcs = ~&alrB^& ~&E?abh/~&alh2fabt2RC @faltPrXlrtPXXPW leql?/~&r ~&l


var lcs // recursive
lcs = Fn.new { |x, y|
    if (x.count == 0 || y.count == 0) return ""
    var x1 = x[0...-1]
    var y1 = y[0...-1]
    if (x[-1] == y[-1]) return lcs.call(x1, y1) + x[-1]
    var x2 = lcs.call(x, y1)
    var y2 = lcs.call(x1, y)
    return (x2.count > y2.count) ? x2 : y2
}

var x = "thisisatest"
var y = "testing123testing"
System.print(lcs.call(x, y))


fcn lcs(a,b){
   if(not a or not b) return("");
   if (a[0]==b[0]) return(a[0] + self.fcn(a[1,*],b[1,*]));
   return(fcn(x,y){if(x.len()>y.len())x else y}(lcs(a,b[1,*]),lcs(a[1,*],b)))
}


begin
    % String literals are enclosed in double-quotes in Algol W.              %
    % There isn't a separate character type but strings of lenghth one can   %
    % be used instead.                                                       %
    % There are no escaping conventions used in string literals, except that %
    % in order to have a double-quote character in a string, two double      %
    % quotes must be used.                                                   %
    % Examples:                                                              %

    % write a single character                                               %
    write( "a" );

    % write a double-quote character                                         %
    write( """" );

    % write a multi-character string - note the "\" is not an escape         %
    % and a\nb will appear on the output, not a and b on separate lines      %
    write( "a\nb" );

end.


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

/* Constantes    */
.equ STDOUT, 1                           @ Linux output console
.equ EXIT,   1                           @ Linux syscall
.equ WRITE,  4                           @ Linux syscall

/* Initialized data */
.data
szMessString:            .asciz "String with final zero \n"
szMessString1:           .string "Other string with final zero \n"
sString:                 .ascii "String without final zero"
                         .byte 0             @ add final zero for display
sLineSpaces:             .byte '>'
                         .fill 10,1,' '      @ 10 spaces
                         .asciz "<\n"        @ add <, CR and final zero for display
sSpaces1:                .space 10,' '       @ other 10 spaces
                         .byte 0             @ add final zero for display
sCharA:                  .space 10,'A'       @ curious !! 10 A with space instruction
                         .asciz "\n"         @ add CR and final zero for display

cChar1:                  .byte 'A'           @ character A
cChar2:                  .byte 0x41          @ character A

szCarriageReturn:        .asciz "\n"

/* UnInitialized data */
.bss

/*  code section */
.text
.global main
main:

    ldr r0,iAdrszMessString
    bl affichageMess                            @ display message
    ldr r0,iAdrszMessString1
    bl affichageMess
    ldr r0,iAdrsString
    bl affichageMess
    ldr r0,iAdrszCarriageReturn
    bl affichageMess
    ldr r0,iAdrsLineSpaces
    bl affichageMess
    ldr r0,iAdrsCharA
    bl affichageMess

100:                                            @ standard end of the program
    mov r0, #0                                  @ return code
    mov r7, #EXIT                               @ request to exit program
    svc 0                                       @ perform system call
iAdrszMessString:         .int szMessString
iAdrszMessString1:        .int szMessString1
iAdrsString:              .int sString
iAdrsLineSpaces:          .int sLineSpaces
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsCharA:               .int sCharA

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                       @ save  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"
    svc #0                                      @ call system
    pop {r0,r1,r2,r7,lr}                        @ restaur registers
    bx lr                                       @ return


str: "Hello world"

print [str "->" type str]

fullLineStr: « This is a full-line string

print [fullLineStr "->" type fullLineStr]

multiline: {
    This
    is a multi-line
    string
}

print [multiline "->" type multiline]

verbatim: {:
    This is
    a verbatim
    multi-line
    string
:}

print [verbatim "->" type verbatim]


"c" ; character
"text" ; string
hereString =   ; with interpolation of %variables%
(
"<>"
the time is %A_Now%
\!
)

hereString2 =  ; with same line comments allowed, without interpolation of variables
(Comments %
literal %A_Now%  ; no interpolation here
)


        c  = "x"
        str= "hello"
	s1 = "abcd"	# simple string
	s2 = "ab\"cd"	# string containing a double quote, escaped with backslash
	print s1
	print s2


10 LET Q$=CHR$(34): REM DOUBLEQUOTES
20 LET D$=Q$+Q$: REM A PAIR OF DOUBLEQUOTES
30 LET S$=Q$+"THIS IS A QUOTED STRING"+Q$
40 PRINT Q$;"HELLO";Q$:REM ADD QUOTES DURING OUTPUT


string path = @"C:\Windows\System32";
string multiline = @"Line 1.
Line 2.
Line 3.";


auto strA = R"(this is
a newline-separated
raw string)";


[\h \e \l \l \o] ; a vector of characters
\uXXXX           ; where XXXX is some hex Unicode code point
\\               ; the backslash character literal


(let ((colon #\:)
      (str "http://www.rosettacode.com/"))
   (format t "colon found at position ~d~%" (position colon str)))


var
  lChar: Char;
  lLine: string;
  lMultiLine: string;
begin
  lChar := 'a';
  lLine := 'some text';
  lMultiLine := 'some text' + #13#10 + 'on two lines';


const s1 := 'quoted "word" in string';
const s2 := "quoted ""word"" in string"; // sames as s1, shows the doubling of the delimiter
const s2 := 'first line'#13#10'second line';   // CR+LF in the middle


let c = '\u0020' //a character
let str = "A string\non several lines!\sAnd you can incorporate expressions: \(c)!"


local :s "String literal"
local :s2 "newline \n carriage return \r tab \t"
!print "backslash \\ quote \q decimal character \{8364}"


'T'                           # character
"The quick brown fox"         # string
`The $kind brown fox`         # "simple" quasiliteral
term`the($adjectives*, fox)`  # "term" quasiliteral


   var c := $65; // character
   var s := "some text"; // UTF-8 literal
   var w := "some wide text"w; // UTF-16 literal
   var s2 := "text with ""quotes"" and
two lines";


IO.puts "Begin String \n============"
str = "string"
str |> is_binary # true


let n= 'N'
let i="Name=\"Nigel Galloway\"\n"
let g= @"Name=""Nigel Galloway""\n"
let e="Nigel
Galloway"
let l= """Name="Nigel Galloway"\n"""
printfn "%c\n%s\n%s\n%s\n%s" n i g e l


      DIMENSION ATWT(12)
      PRINT 1
    1 FORMAT (12HElement Name,F9.4)
      DO 10 I = 1,12
        READ  1,ATWT(I)
   10   PRINT 1,ATWT(I)
      END


Print "Hello, World."
Print Chr(34); "Hello, World." & Chr(34)

Print "Tom said, ""The fox ran away."""
Print "Tom said," + "'The fox ran away.'"


echo Quotes are optional in most cases.
echo
echo 'But they are when using either of these characters (or whitespace):'
echo '# $ % ^ & * ( ) { } ; \' " \\ < > ?'
echo
echo Single quotes only interpolate \\ and \' sequences.
echo '\In \other \cases, \backslashes \are \preserved \literally.'
echo
set something variable
echo "Double quotes interpolates \\, \" and \$ sequences and $something accesses."


IsChar('a');
# true
IsString("abc");
# true
IsString('a');
# false
IsChar("a");
# false


"abcdef" == "abc\
            \def"

"abc\ndef" == "abc\n\
              \def"


CHARACTER c1='A', c2="B", c3=&C&
CHARACTER str1='single quotes', str2="double quotes", str3*100

str3 = % delimit "Nested 'strings' " if needed %


procedure main()

   # strings are variable length are not NUL terminated
   # at this time there is no support for unicode or multi-byte charactersets

   c1 := 'aaab'                                          # not a string - cset
   s1 := "aaab"                                          # string
   s2 := "\"aaab\b\d\e\f\n\l\n\r\t\v\'\"\\\000\x00\^c"   # with escapes and imbedded zero

   # no native variable substitution, a printf library function is available in the IPL

   every x := c1|s1|s2 do                                # show them
      write(" size=",*x,", type=", type(x),", value=", image(x))
end


a = " that's a string "
b = ' a "string" is this '


Home is a room. The description is "This is where you live...

...with your [number of animals in Home] pet[s]."


'x'                   NB.  Scalar character
'string'              NB.  List of characters, i.e. a string
'can''t get simpler'  NB.  Embedded single-quote


  char a = 'a';  // prints as: a
  String b = "abc";  // prints as: abc
  char doubleQuote = '"';  // prints as: "
  char singleQuote = '\'';  // prints as: '
  String singleQuotes = "''";  // prints as: ''
  String doubleQuotes = "\"\"";  // prints as: ""


greet = "Hello"
whom = "world"
greet * ", " * whom * "."


// version 1.0.6

fun main(args: Array<String>) {
    val cl = 'a'          // character literal - can contain escaped character
    val esl = "abc\ndef"  // escaped string literal - can contain escaped character(s)
    val rsl = """
              This is a raw string literal
              which does not treat escaped characters
              (\t, \b, \n, \r, \', \", \\, \$ and \u)
              specially and can contain new lines.

              "Quotes" or doubled ""quotes"" can
              be included without problem but not
              tripled quotes.
              """
    val msl = """
              |Leading whitespace can be removed from a raw
              |string literal by including
              |a margin prefix ('|' is the default)
              |in combination with the trimMargin function.
              """.trimMargin()
    println(cl)
    println(esl)
    println(rsl)
    println(msl)
}


'I\'m a 2" string\n'
"I'm a 2\" string\n"


\documentclass{minimal}
\begin{document}
`a' is for ``apple"
\end{document}


'Liberty BASIC does not support escape characters within literal strings.
print "Quotation mark:"
print chr$(34)
print

'Print literal string
print "Hello, World."
'Print literal string displaying quotation marks.
print chr$(34) + "Hello, World." + chr$(34)


str = "Hello "&QUOTE&"world!"&QUOTE
put str
-- "Hello "world!""


put "Literal string"  -- Literal string
put char 1 of "Literal string"  -- L
put char 1 to 7 of "Literal string"  -- Literal
put word 1 of "Literal string"  -- Literal
put quote & "string" & quote -- "string"


print "Hello\,\ world
print "|Hello, world|


singlequotestring = 'can contain "double quotes"'
doublequotestring = "can contain 'single quotes'"
longstring = [[can contain
               newlines]]
longstring2 = [==[ can contain [[ other ]=] longstring " and ' string [===[ qualifiers]==]


Print "Hello {World}"
Print {Hello "World"}
Report {Multiline String
      2nd line
      }
Print """Hello There"""={"Hello There"}
Print Quote$("Hello There")={"Hello There"}


print(255)        // decimal literal
print(0000'00FF)  // hexadecimal literal
print(00'FF)      // short hexadecimal literal
print(F'F)        // ultrashort (single-byte) hexadecimal literal
print(377o)       // octal literal
print(1111'1111b) // binary literal
print(255'000)    // decimal literal


> "foobar";
                                "foobar"

> "foo\nbar"; # string with a newline
"foo
    bar"

> "c"; # a character
                                  "c"


There is no character type in Mathematica, only string type.
"c";          // String (result: "c")
"\n";         // String (result: newline character)


    s1 = 'abcd'   % simple string
    s2 = 'ab''cd'   % string containing a single quote


/* A string */
"The quick brown fox jumps over the lazy dog";

/* A character - just a one character string */
"a"


;These are all equivalent:
LDA #$41
LDA #65
LDA #%01000001
LDA #'A'


;These are all equivalent:
MOVE.B #$41,D0
MOVE.B #65,D0
MOVE.B #%01000001,D0
MOVE.B #'A',D0


MOV AX,4C00h
MOV BX,%1111000011110000
MOV CX,0xBEEF
MOV DL,35


.equ STDOUT, 1
.equ SVC_WRITE, 64
.equ SVC_EXIT, 93

.text
.global _start

_start:
	stp x29, x30, [sp, -16]!
	mov x29, sp
	mov x0, #123 // decimal
	bl print_uint64
	mov x0, #0b01111011 // binary
	bl print_uint64
	mov x0, #0173 // octal
	bl print_uint64
	mov x0, #0x7b // hexadecimal
	bl print_uint64
	mov x0, #'{ // ascii value
	bl print_uint64
	mov x0, #'\{ // ascii value in another way
	bl print_uint64
	ldp x29, x30, [sp], 16
	mov x0, #0
	b _exit // exit(0);

// void print_uint64(uint64_t x) - print an unsigned integer in base 10.
print_uint64:
	// x0 = remaining number to convert
	// x1 = pointer to most significant digit
	// x2 = 10
	// x3 = x0 / 10
	// x4 = x0 % 10
	// compute x0 divmod 10, store a digit, repeat if x0 > 0
	ldr x1, =strbuf_end
	mov x2, #10
1:	udiv x3, x0, x2
	msub x4, x3, x2, x0
	add x4, x4, #48
	mov x0, x3
	strb w4, [x1, #-1]!
	cbnz x0, 1b
	// compute the number of digits to print, then call write()
	ldr x3, =strbuf_end_newline
	sub x2, x3, x1
	mov x0, #STDOUT
	b _write

.data
strbuf:
	.space 31
strbuf_end:
	.ascii "\n"
strbuf_end_newline:
.align 4

.text
//////////////// system call wrappers
// ssize_t _write(int fd, void *buf, size_t count)
_write:
	stp x29, x30, [sp, -16]!
	mov x8, #SVC_WRITE
	mov x29, sp
	svc #0
	ldp x29, x30, [sp], 16
	ret

// void _exit(int retval)
_exit:
	mov x8, #SVC_EXIT
	svc #0


with Ada.Integer_Text_IO;  use Ada.Integer_Text_IO;

procedure Test_Literals is
begin
   Put (16#2D7#);
   Put (10#727#);
   Put (8#1_327#);
   Put (2#10_1101_0111#);
end Test_Literals;


MCSKIP "WITH" NL
"" Literals/String
MCINS %.
MCSKIP MT,<>
"" Demonstration of literal string
MCDEF Bob AS Alice
"" The following two lines both mention Bob. The first line is
"" evaluated, but the second is surrounded by literal brackets and is not
"" evaluated.
This is the first mention of Bob
<and here we mention Bob again>


USER>SET S1="ABC"

USER>SET S2="""DEF"""

USER>SET S3="""GHI"

USER>W S1
ABC
USER>W S2
"DEF"
USER>W S3
"GHI


'a'                                              // character literal
'\n'                                             // also a character literal
"foo\nbar"                                       // string literal
@"x\n"                                           // same as "x\\n"
@"x
 y"                                              // same as "x\n y"
@"""Hi!"""                                       // "" replaces \" to escape a literal quote mark
<#This string type can contain any symbols including "
and new lines. It does not support escape codes
like "\n".#>                                     // same as "This string type can contain any symbols including \"\nand new lines. "
                                                 //       + "It does not\nsupport escape codes\nlike \"\\n\"."
<#Test <# Inner #> end#>                         // same as "Test <# Inner #> end" (i.e. this string type support recursion.


var c = 'c'
var s = "foobar"
var l = """foobar
and even
more test here"""

var f = r"C:\texts\text.txt" # Raw string


main:(

  SHORT SHORT INT ssdec = SHORT SHORT 727,
            sshex = ABS SHORT SHORT 16r2d7,
            ssoct = ABS SHORT SHORT 8r1327,
            ssbin = ABS SHORT SHORT 2r1011010111;

  SHORT INT sdec = SHORT 727,
            shex = ABS SHORT 16r2d7,
            soct = ABS SHORT 8r1327,
            sbin = ABS SHORT 2r1011010111;

  INT dec = 727,
      hex = ABS 16r2d7,
      oct = ABS 8r1327,
      bin = ABS 2r1011010111;

  LONG INT ldec = LONG 727,
           lhex = ABS LONG 16r2d7,
           loct = ABS LONG 8r1327,
           lbin = ABS LONG 2r1011010111;

CO
  LONG LONG INT lldec = LONG LONG 727,
           llhex = ABS LONG LONG 16r2d7,
           lloct = ABS LONG LONG 8r1327,
           llbin = ABS LONG LONG 2r1011010111
# etc ... #
END CO

  print(("SHORT SHORT INT:", ssdec, sshex, ssoct, ssbin, new line));
  print(("      SHORT INT:", sdec, shex, soct, sbin, new line));
  print(("            INT:", dec, hex, oct, bin, new line));
  print(("       LONG INT:", ldec, lhex, loct, lbin, new line))
CO LONG LONG INT not supported by ELLA ALGOL 68RS
  print(("LONG LONG INT:", new line, lldec, new line, llhex, new line, lloct, new line, llbin, new line))
# etc ... #
END CO

)


begin
    write( 16, number( #10 ) )
end.


    s1 = 'abcd'   % simple string
    s2 = 'ab''cd'   % string containing a single quote using an escaped single quote
    s3 = 'ab"cd'   % simple string containing a double quote
    s4 = "ab'cd"   % string containing a single quote
    s5 = "ab""cd"   % string containing a double quote using an escaped double quote


PROC main()
  IF ($2d7 = 727) AND (%001011010111 = 727) THEN WriteF('true\n')
ENDPROC


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

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall

/*********************************/
/* Initialized data              */
/*********************************/
.data
iNumberBinaire: .int 0b1100100
iNumberOctal:    .int  0144
iNumberDecimal: .int 100
iNumberHexa:     .int 0x64

szMessResult:  .ascii "Resultat = "      @ message result
sMessValeur:   .fill 12, 1, ' '
                   .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                @ entry of program
    push {fp,lr}      @ saves 2 registers
    ldr r0,iAdriNumberBinaire   @ number address
    ldr r0,[r0]                     @ load number
    ldr r1,iAdrsMessValeur
    bl conversion10       @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdriNumberOctal
    ldr r0,[r0]
    ldr r1,iAdrsMessValeur
    bl conversion10       @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
   ldr r0,iAdriNumberDecimal
    ldr r0,[r0]
    ldr r1,iAdrsMessValeur
    bl conversion10       @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdriNumberHexa
    ldr r0,[r0]
    ldr r1,iAdrsMessValeur
    bl conversion10       @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message

100:   @ standard end of the program
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    svc #0                       @ perform the system call
iAdriNumberBinaire:	.int iNumberBinaire
iAdriNumberOctal:		.int iNumberOctal
iAdriNumberDecimal:	.int iNumberDecimal
iAdriNumberHexa:		.int iNumberHexa
iAdrsMessValeur:		.int sMessValeur
iAdrszMessResult:		.int szMessResult

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}    			/* save  registres */
    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" */
    svc #0                      /* call systeme */
    pop {r0,r1,r2,r7,lr}    				/* restaur des  2 registres */
    bx lr	        			/* return  */
/******************************************************************/
/*     Converting a register to a decimal                                 */
/******************************************************************/
/* r0 contains value and r1 address area   */
conversion10:
    push {r1-r4,lr}    /* save registers */
    mov r3,r1
    mov r2,#10

1:	   @ start loop
    bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48        @ digit
    strb r1,[r3,r2]  @ store digit on area
    sub r2,#1         @ previous position
    cmp r0,#0         @ stop if quotient = 0 */
    bne 1b	          @ else loop
    @ and move spaves in first on area
    mov r1,#' '   @ space
2:
    strb r1,[r3,r2]  @ store space in area
    subs r2,#1       @ @ previous position
    bge 2b           @ loop if r2 >= zéro

100:
    pop {r1-r4,lr}    @ restaur registres
    bx lr	          @return
/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */
/* r1 remainder  */
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 */
   .align 4
.Ls_magic_number_10: .word 0x66666667


'a'
'\''
"abcd"
"ab\ncd"
"ab\" and \" cd"


declare
Digit0 = &0       %% the character '0'
NewLine = &\n     %% a character with special representation
NewLine = &\012   %% characters can also be specified with octals

%% Strings are lists of characters, but can also be written in double quotes:
[&H &e &l &l &o] = "Hello"

AnAtom = 'Hello'         %% single quotes are used for atoms
Atom2 = hello = 'hello'  %% for atoms starting with a lower case letter, they are optional

%% To build strings out of other values, so-called virtual strings are used:
MyName = "Peter"
MyAge = 8
{System.showInfo MyName # " is " # MyAge # " years old."}


'c';                      # character
'hello';                  # these two strings are the same
"hello";
'Hi $name. How are you?'; # result: "Hi $name. How are you?"
"Hi $name. How are you?"; # result: "Hi Bob. How are you?"
'\n';                     # 2-character string with a backslash and "n"
"\n";                     # newline character
`ls`;                     # runs a command in the shell and returns the output as a string
q/hello/;                 # same as 'hello', but allows custom delimiters, eg: q(hi) and q!hi!
qq/hello/;                # same as "hello", but allows custom delimiters, eg: qq{$hi} and qq#hi#
qw/one two three/;        # same as ('one', 'two', 'three'); constructs a list of the words
qx/ls/;                   # quoted execution, same as `ls`
qr/regex/;                # creates a regular expression
<<END;                    # Here-Document
Hi, whatever goes here gets put into the string,
including newlines and $variables,
until the label we put above
END
<<'END';                  # Here-Document like single-quoted
Same as above, but no interpolation of $variables.
END


constant UPPERCASEJ = 'J'   -- equivalent to 74


'c';                      # character
'hello';                  # these two strings are the same
"hello";
'Hi $name. How are you?'; # result: "Hi $name. How are you?"
"Hi $name. How are you?"; # result: "Hi Bob. How are you?"
'\n';                     # 2-character string with a backslash and "n"
"\n";                     # newline character
`ls`;                     # runs a command in the shell and returns the output as a string
<<END                     # Here-Document
Hi, whatever goes here gets put into the string,
including newlines and $variables,
until the label we put above
END;
<<'END'                   # Here-Document like single-quoted
Same as above, but no interpolation of $variables.
END;


'c';          // Character code (ASCII) (result: 99)
"c";          // String (result: "c")
"\n";         // String (result: newline character)
"hi " + world // String (result: "hi " and the contents of the variable world)
#"multiple line
string using the
preprocessor" // single literal string with newlines in it


'H'                  /* a single character as a literal.             */
'this is a string'
''                   /* an empty string literal.                     */
'John''s cat'        /* a literal containing an embedded apostrophe. */
                     /* stored are <<John's cat>>                    */
'101100'b            /* a bit string, stored as one bit per digit.   */


'a'    ;;; string consisting of single character


#include <iostream>

int main()
{
  std::cout << ( (727 == 0x2d7) &&
                 (727 == 01327)     ? "true" : "false")
            << std::endl;

  return 0;
}


; Characters (*.c), can be ASCII or UNICODE depending on compiler setting
Define.c  AChar='A'
; defines as *.a it will be ASCII and *.u is always UNICODE
Define.a  A='b'
Define.u  U='水'

; Strings is defined as **.s or ending with '$'
Define.s  AStrion     ="String #1"
Define    BStrion.s   ="String #2"
Define    CString$    ="String #3"
; Fixed length stings can be defined if needed
Define XString.s{100} ="I am 100 char long!"

; '"' can be included via CHR() or its predefined constant
Define AStringQuotes$=Chr(34)+"Buu"+Chr(34)+" said the ghost!"
Define BStringQuotes$=#DOUBLEQUOTE$+"Buu"+#DOUBLEQUOTE$+" said yet a ghost!"


'c' == "c" # character
'text' == "text"
' " '
" ' "
'\x20' == ' '
u'unicode string'
u'\u05d0' # unicode literal


/O> char X emit
... char Y emit
... char Z emit cr
... $ "This is a 'string'." echo$ cr
... $ 'This is a "string" too.' echo$ cr
... $ ~This is one with "quotes" and 'apostrophes'.~ echo$ cr
... $ \Any non-whitespace character can be the delimiter.\ echo$ cr
...
XYZ
This is a 'string'.
This is a "string" too.
This is one with "quotes" and 'apostrophes'.
Any non-whitespace character can be the delimiter.


str1 <- "the quick brown fox, etc."
str2 <- 'the quick brown fox, etc.'
identical(str1, str2)   #returns TRUE


prompt$ cobc -x -cb_conf=acucobol-literals:ok


IF 37=$25 THEN PRINT "True"
IF 37=%00100101 THEN PRINT "True"


import std.stdio, std.conv;

void main() {
    writeln("oct: ", octal!777);
    writeln("bin: ", 0b01011010);
    writeln("hex: ", 0xBADF00D);
    writeln("dec: ", 1000000000);
    writeln("dec: ", 1_000_000_000);
    writeln();

    writeln(typeid(typeof(0)));
    writeln(typeid(typeof(0u)));
    // writeln(typeid(typeof(0l))); // 'l' suffix is deprecated
    writeln(typeid(typeof(0L)));
    writeln(typeid(typeof(0uL)));
    writeln(typeid(typeof(0LU)));
    writeln();

    writefln("%x", 0xFEE1_BAD_CAFE_BABEuL);
}


Short       Long            Meaning
=====       ====            =======
:x          :exec           Execute as command and return results
:w          :words          Split result on words (no quote protection)
:ww         :quotewords     Split result on words (with quote protection)
:v          :val            Evaluate word or words for value literals
:q          :single         Interpolate \\, \q and \' (or whatever)
:qq         :double         Interpolate with :s, :a, :h, :f, :c, :b
:s          :scalar         Interpolate $ vars
:a          :array          Interpolate @ vars
:h          :hash           Interpolate % vars
:f          :function       Interpolate & calls
:c          :closure        Interpolate {...} expressions
:b          :backslash      Interpolate \n, \t, etc. (implies :q at least)
:to         :heredoc        Parse result as heredoc terminator
            :regex          Parse as regex
            :subst          Parse as substitution
            :trans          Parse as transliteration
            :code           Quasiquoting
:p          :path           Return a Path object (see S16 for more options


char1 = "A"
char2 = 'A'
str = "this is a string"
another = 'this is also a string'
escape1 = "that's it!"
escape2 = 'that''s it!'


'single quotes with \'embedded quote\' and \\backslash'
%q(not interpolating with (nested) parentheses
and newline)


const
  DEC_VALUE = 256;        // decimal notation
  HEX_VALUE = $100;       // hexadecimal notation
  BIN_VALUE = %100000000; // binary notation (since Delphi 10.4 version)


var a : Integer := 42;
var b : Integer := $2a;


42        // a decimal integer
#x2A      // a hexadecimal integer
#o52      // an octal integer
#b101010  // a binary integer


? 256
# value: 256

? 0x100
# value: 256

? 0123
# syntax error: Octal is no longer supported: 0123


% String literals
variable c, ch, s, b, r, v;

c = 'A';
ch = '\x{1d7bc}';

printf("Double quotes\n");
s = "this is a single line string with\t\tbackslash substitutions";
() = fputs(s, stdout);
() = fputs("\n", stdout);

s = "this is a single line string without\t\tbackslash substitutions"R;
() = fputs(s, stdout);
() = fputs("\n", stdout);

s = "string with backslash escaped newline \
takes up two lines in source, but no newline is in the string";
() = fputs(s, stdout);
() = fputs("\n", stdout);

printf("\nBack quotes\n");
r = `this is a multi line string with
  backslash substitutions and \t(tabs)\t`Q;
() = fputs(r, stdout);
() = fputs("\n", stdout);

r = `this is a multi line string without
  backslash substitutions and \t(tabs)\t`;
() = fputs(r, stdout);
() = fputs("\n", stdout);

printf("\nvariable substitution\n");
v = "variable substitution with $$c as $c"$;
() = fputs(v, stdout);
() = fputs("\n", stdout);

v = "no variable substitutions, $$c as $c";
() = fputs(v, stdout);
() = fputs("\n", stdout);

printf("\nBString_Type\n");
b = "this is a binary string, NUL \0 \0 bytes allowed"B;
print(b);
% display of b will be stopped at the NUL byte using stdio streams
() = fputs(b, stdout);
() = fputs("\n", stdout);
printf("strlen(b) is %d, bstrlen(b) is %d\n", strlen(b), bstrlen(b));


123		-- decimal
-1_2_3		-- decimal
0x7b		-- hexadecimal
0c173		-- octal
0b111_1011	-- binary


   var n := 1234; // decimal number
   var x := 1234h; // hexadecimal number


123      ;; decimal           all Emacs
#b101    ;; binary            Emacs 21 up, XEmacs 21
#o77     ;; octal             Emacs 21 up, XEmacs 21
#xFF     ;; hex               Emacs 21 up, XEmacs 21
#3r210   ;; any radix 2-36    Emacs 21 up (but not XEmacs 21.4)


'single quotes with \'embedded quote\' and \\backslash';
‚unicode single quoted’;
%q(not interpolating with (nested) parentheses
and newline);


let you = "You"
let str1 = "\(you) can insert variables into strings."
let str2 = "Swift also supports unicode in strings ı∫ƒ∂ß´™¡à"
let str3 = "Swift also supports control characters \n\tLike this"
let str4 = "'" // '
let str5 = "\"" // "
println(str3)


set str "This is Tcl $::tcl_version\tIt is [clock format [clock seconds]]"
puts $str ;# ==> This is Tcl 8.5	It is Mon Apr 06 16:49:46 EDT 2009


str = "I'm a string. \"You can quote me\". Name\tJos\u00E9\nLocation\tSF."


10 . ! decimal
0b10 . ! binary
-0o10 . ! octal
0x10 . ! hexadecimal


;; Fennel, like Lua, supports base 10 and hex literals (with a leading 0x).
1234      ;1234
0x1234    ;4660

;; Optionally, underscores can be used to split numbers into readable chunks.
123_456_789    ;123456789
0x1234_5678    ;305419896


HEX
FEEDFACE
2 BASE !
1011001
DECIMAL
1234
: mask  var @ [ base @ hex ] 3fff and [ base ! ] var ! ;


program IntegerLiteral

  implicit none
  integer, parameter   :: dec = 727
  integer, parameter   :: hex = Z'2d7'
  integer, parameter   :: oct = O'1327'
  integer, parameter   :: bin = B'1011010111'

  print *, dec, hex, oct, bin

end program IntegerLiteral


$$ MODE TUSCRIPT,{}
s1=*
DATA "string"
s2=*
DATA + "double" quotes
s3=*
DATA + 'single' quotes
s4=*
DATA + "double" + 'single' quotes
show=JOIN(s1," ",s2,s3,s4)
show=JOIN(show)
PRINT show


echo "The boy said 'hello'."
echo 'The girl said "hello" too.'


  Debug.Print "Tom said, ""The fox ran away."""
  Debug.Print "Tom said, 'The fox ran away.'"


' FB 1.05.0 Win64

' The following all print 64 to the console

' integer literals of unspecified type - actual type is inferred from size or context (8, 16, 32 or 64 bit signed/unsigned)
Print 64        '' Decimal literal
Print &H40      '' Hexadecimal literal
Print &O100     '' Octal Literal
Print &B1000000 '' Binary literal

' integer literals of specific types
' Integer type is 4 bytes on 32 bit and 8 bytes on 64 bit platform
Print 64%       '' Decimal signed 4/8 byte integer (Integer)
Print 64L       '' Decimal signed 4 byte integer   (Long)
Print 64&       '' Decimal signed 4 byte integer   (Long) - alternative suffix
Print 64LL      '' Decimal unsigned 4 byte integer (ULong)
Print 64LL      '' Decimal signed 8 byte integer   (LongInt)
Print 64ULL     '' Decimal unsigned 8 byte integer (ULongInt)

Sleep


123456789123456789               // (a number in base 10)
123_456_789_123_456_789          // (the same number in base 10 with underscores for readability)
1 quadrillion                    // (named numbers are fine in Frink.)
1ee39                            // (exact exponent, an integer with exact value 10^39)
6.02214076ee23                   // (exact exponent, Avogadro's number now defined as the exact integer 602214076000000000000000 )
100001000101111111101101\\2      // (a number in base 2)
1000_0100_0101_1111_1110_1101\\2 // (a number in base 2 with underscores for readability)
845FED\\16                       // (a number in base 16... bases from 2 to 36 are allowed)
845fed\\16                       // (The same number in base 16... upper or lowercase are allowed.)
845_fed\\16                      // (a number in base 16 with underscores for readability)
FrinkRulesYou\\36                // (a number in base 36)
0x845fed                         // (Common hexadecimal notation)
0x845FED                         // (Common hexadecimal notation)
0xFEED_FACE                      // (Hexadecimal with underscores for readability)
0b100001000101111111101101       // (Common binary notation)
0b1000_0100_0101_1111_1110_1101  // (Binary with underscores for readability)


window 1

printf @"     Decimal: %ld", 100
printf @" Hexadecimal: %x",  100
printf @"       Octal: %o",  100
print  @"      Binary: ";  bin$(100)

HandleEvents


package main

import "fmt"

func main() {
	fmt.Println(727 == 0x2d7)         // prints true
	fmt.Println(727 == 01327)         // prints true
	fmt.Println(727 == 0b10110_10111) // prints true
	fmt.Println(727 == '˗')           // prints true
}


Dim s = "Tom said, ""The fox ran away."""
Result: Tom said, "The fox ran away."


Dim s As String = "Tom said, ""The fox ran away."""
Result: Tom said, "The fox ran away."


The literal value of a character is specified by preceding it with a
caret. For example, this assigns the ASCII value of A (hex 41) to Ch:

Ch:= ^A;

Strings are one-dimensional byte arrays.
For example, this assigns the address of the string enclosed in quote marks to Str:

Str:= "Hello, world!";

The ASCII code for each character is stored in sequential bytes.
By default strings are terminated with the most significant bit set
on the last character.
The exclamation point would be stored as hex A1.
Strings can also be terminated with a zero byte (like in the C language).
If the command:

string 0;

occurs anywhere before a string is set up then it will have an extra zero
byte at the end.

A quote mark can be included in a string by preceding it with a caret.
Carets are also included this way.
For example:

"^"^^^" is a ^"caret^""

results in:

"^" is a "caret"

Carets can also be used to specify control characters.
For example, this is escape E (hex 1B C5):

"^[E"

Strings can any length and can span lines, for example:

"Hello,
world!"

A carriage return (hex 0D) and line feed (hex 0A) are in the middle.

Strings are output to various devices (such as the console screen or
printer) with the Text intrinsic.


println 025    // octal
println 25     // decimal integer
println 25l    // decimal long
println 25g    // decimal BigInteger
println 0x25   // hexadecimal


Prelude> 727 == 0o1327
True
Prelude> 727 == 0x2d7
True


# All equal to 15
println 15
println 000015 # Leading zeros are ignored
println 0b1111
println 0o17
println 0xf


U8 i; // 8 bit integer
U16 i; // 16 bit integer
U32 i; // 32 bit integer
U64 i; // 64 bit integer


public class IntegerLiterals {
    public static void main(String[] args) {
        System.out.println( 727 == 0x2d7 &&
                            727 == 01327   );
    }
}


// version 1.0.6

fun main(args: Array<String>) {
    val d = 255                  // decimal integer literal
    val h = 0xff                 // hexadecimal integer literal
    val b = 0b11111111           // binary integer literal

    val ld = 255L                // decimal long integer literal (can't use l instead of L)
    val lh = 0xffL               // hexadecimal long integer literal (could use 0X rather than 0x)
    val lb = 0b11111111L         // binary long integer literal (could use 0B rather than 0b)

    val sd : Short = 127         // decimal integer literal automatically converted to Short
    val sh : Short = 0x7f        // hexadecimal integer literal automatically converted to Short
    val bd : Byte  = 0b01111111  // binary integer literal automatically converted to Byte

    println("$d $h $b $ld $lh $lb $sd $sh $bd")
}


implement Command;

include "sys.m";
sys: Sys;

include "draw.m";

include "sh.m";

init(nil: ref Draw->Context, nil: list of string)
{
	sys = load Sys Sys->PATH;

	sys->print("%d\n", 2r1111); # binary
	sys->print("%d\n", 8r17);   # octal
	sys->print("%d\n", 15);     # decimal
	sys->print("%d\n", 16rF);   # hexadecimal
}


:- object(integers).

    :- public(show/0).

    show :-
        write('Binary      0b11110101101 = '), write(0b11110101101), nl,
        write('Octal       0o3655 =        '), write(0o3655), nl,
        write('Decimal     1965 =          '), write(1965), nl,
        write('Hexadecimal 0x7AD =         '), write(0x7AD), nl.

:- end_object.


Def ExpType$(x)=Type$(x)
Print ExpType$(12345678912345#)="Currency", 12345678912345#
Print ExpType$([email protected])="Decimal", [email protected]
Print ExpType$(12&)="Long", 12&, 0xFFFFFFFF&=-1
Print ExpType$(12%)="Integer", 12%, 0xFFFF%=-1
\\ used for unsigned integers (but it is double)
Print ExpType$(0xFFFFFFFF)="Double", 0xFFFFFFFF=4294967295


eval(10)        # base 10
eval(010)       # base 8
eval(0x10)      # base 16


b^^nnnn is a valid number in base b (with b ranging from 2 to 36) :
2^^1011
-> 11

36^^1011
-> 46693


Bin = 0b010101,
Octal = 0o666,
Hex = 0x1fa,
CharCode = 0'a.


MODULE Literals EXPORTS Main;

IMPORT IO;

BEGIN
  IO.PutInt(16_2D7);
  IO.Put(" ");
  IO.PutInt(10_727);
  IO.Put(" ");
  IO.PutInt(8_1327);
  IO.Put(" ");
  IO.PutInt(2_1011010111);
  IO.Put("\n");
END Literals.


/**
 Integer literals, in Neko
 Base 10 and Base 16, no leading zero octal in Neko
*/

var num = 2730
if (num == 02730) $print("base 10, even with leading zero\n")
if (num == 0xAAA) $print("base 16, with leading 0x or 0X\n")


42                            // integer literal
1_000_000                     // _ can be used for readability
1_42_00                       // or unreadability...
0x2a                          // hexadecimal integer literal
0o52                          // octal integer literal
0b101010                      // binary integer literal
10u                           // unsigned int
10b, 10sb, 10bs               // signed byte
10ub, 10bu                    // unsigned byte
10L                           // long
10UL, 10LU                    // unsigned long


bundle Default {
  class Literal {
    function : Main(args : String[]) ~ Nil {
      (727 = 0x2d7)->PrintLine();
    }
  }
}


# 727 = 0b1011010111;;
- : bool = true
# 727 = 0o1327;;
- : bool = true
# 727 = 0x2d7;;
- : bool = true
# 12345 = 12_345 (* underscores are ignored; useful for keeping track of places *);;
- : bool = true


try
   %% binary      octal   dec.  hexadecimal
   0b1011010111 = 01327 = 727 = 0x2d7
   {Show success}
catch _ then
   {Show unexpectedError}
end


const

    DEC_VALUE    =    15;
    HEX_VALUE    =    $F;
    OCTAL_VALUE  =  &017;
    BINARY_VALUE = %1111;


print "true\n" if ( 727 == 0x2d7 &&
                    727 == 01327 &&
                    727 == 0b1011010111 &&
                    12345 == 12_345   # underscores are ignored; useful for keeping track of places
                  );


<?php
if (727 == 0x2d7 &&
    727 == 01327) {
  echo "true\n";
}

$a = 1234; // decimal number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
$a = 1_234_567; // decimal number (as of PHP 7.4.0)


% All outputs are in base 10
main =>
  println(100),                                % plain integer
  println(1_234_567_890),                      % underscores can be used for clarity
  println(1_000_000_000_070_000_030_000_001),  % arbitrary precision
  nl,

  println(0x10ABC),                            % Hexadecimal
  println(0xBe_ad_ed_83),                      % lower or upper case are the same
  nl,

  println(0o666),                              % Octal
  println(0o555_666_777),
  nl,

  println(0b1111111111111),                    % binary
  println(0b1011_1111_1110)


12345
'b4'xn           /* a hexadecimal literal integer.            */
'ffff_ffff'xn    /* a longer hexadecimal hexadecimal integer. */
1101b             /* a binary integer, of value decimal 13.   */


>>> # Bin(leading 0b or 0B), Oct(leading 0o or 0O), Dec, Hex(leading 0x or 0X), in order:
>>> 0b1011010111 == 0o1327 == 727 == 0x2d7
True
>>>


[ 2 base put ] now!

( The Quackery compiler now expects numeric literals to be in binary.   )

[ base release ] now!

( The Quackery compiler now expects numeric literals to be in whichever
  base they were previously. The default base is decimal.               )


0x2d7==727            # TRUE
identical(0x2d7, 727) # TRUE
is.numeric(727)       # TRUE
is.integer(727)       # FALSE
is.integer(727L)      # TRUE
is.numeric(0x2d7)     # TRUE
is.integer(0x2d7)     # FALSE
is.integer(0x2d7L)    # TRUE


#100 ( decimal )
%100 ( binary  )
$100 ( hex     )
'c   ( ascii character )
100  ( number in current base )


/*REXX pgm displays an  integer  (expressed in the pgm as a literal)  in different bases*/
                                      /*────────── expressing decimal numbers ──────────*/
ddd =  123                            /*a decimal number  (expressed as a literal).     */
ddd = '123'                           /*this is exactly the same as above.              */
ddd = "123"                           /*this is exactly the same as above also.         */
                                      /*────────── expressing hexadecimal numbers ──────*/
hhh = '7b'x                           /*a value,  expressed as a hexadecimal literal.   */
hhh = '7B'x                           /* (same as above)  using a capital  "B".         */
hhh = '7B'X                           /* (same as above)  using a capital  "X".         */
cow = 'dead beef'x                    /*another value,    with a blank for the eyeballs.*/
cow = 'de ad be ef'x                  /* (same as above)  with  blanks for the eyeballs.*/
                                      /*────────── expressing binary numbers ───────────*/
bbb =  '1111011'b                     /*a value,  expressed as a binary literal.        */
bbb = '01111011'b                     /* (same as above)  with a full 8 binary digits.  */
bbb = '0111 1011'b                    /* (same as above)  with a blank for the eyeballs.*/

say '    base  10='            ddd
say '    base   2='  x2b( d2x( ddd ) )
say '    base  16='       d2x( ddd )
say '    base 256='       d2c( ddd )  /*the output displayed is ASCII (or maybe EBCDIC).*/

thingy1=  +123                        /*╔══════════════════════════════════════════════╗*/
thingy2= '+123'                       /*║ All of the THINGYs variables aren't strictly ║*/
thingy3= ' 123'                       /*║ (exactly)  equal to the  DDD  variable,  but ║*/
thingy4=   123.                       /*║ they do compare numerically equal.   When    ║*/
thingy5=    12.3e+1                   /*║ compared numerically, numbers are rounded to ║*/
thingy6=  1230e-1                     /*║ the current setting of  NUMERIC DIGITS.  The ║*/
thingy7=  1230E-0001                  /*║ default for  (decimal)  NUMERIC DIGITS is  9 ║*/
thingy8= ' +     123  '               /*╚══════════════════════════════════════════════╝*/

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


see "Decimal literal = " + 1234 + nl
see "Hexadecimal literal = " + dec("4D2") + nl
see "Octal Literal = " + octal(668) + nl
see "Binary literal = " + bintodec("10011010010")

func bintodec(bin)
     binsum = 0
     for n=1  to len(bin)
         binsum = binsum + number(bin[n]) *pow(2, len(bin)-n)
     next
     return binsum

func octal m
     output = ""
     w = m
     while fabs(w) > 0
           oct = w & 7
           w = floor(w / 8)
           output = string(oct) + output
     end
     return output


727 == 0b1011010111  # => true, binary
727 == 0x2d7   # => true, hex
727 == 0o1327  # => true, octal
727 == 01327   # => true, octal

12345 == 12_345 # => true underscores are ignored; useful for keeping track of places


10     // Decimal
0b10   // Binary
0x10   // Hexadecimal
0o10   // Octal
1_000  // Underscores may appear anywhere in the numeric literal for clarity
10_i32 // The type (in this case i32, a 32-bit signed integer) may also be appended.
10i32  // With or without underscores


scala> 16
res10: Int = 16

scala> 020L
res11: Long = 16

scala> 0x10 : Byte
res12: Byte = 16

scala> 16 : Short
res13: Short = 16

scala> 020 : Int
res14: Int = 16

scala> 0x10 : Long
res15: Long = 16


$ include "seed7_05.s7i";

const proc: main is func
  begin
    writeln(727);
    writeln(32#MN);
    writeln(16#2D7);
    writeln(10#727);
    writeln(8#1327);
    writeln(2#1011010111);
  end func;


- 727 = 0x2d7;
val it = true : bool
- 727 = Word.toInt 0w727;
val it = true : bool
- 0w727 = 0wx2d7;
val it = true : bool
- ~727; (* negative number;
         * ~ is the unary negation operator for all numbers, including reals and ints;
         * worth mentioning because it's unusual
         *)
val it = ~727 : int


let hex = 0x2F // Hexadecimal
let bin = 0b101111 // Binary
let oct = 0o57 // Octal


Sub Main()

'Long:    4 Bytes (signed), type specifier = &
Dim l1 As Long, l2 As Long, l3 As Long
'Integer: 2 Bytes (signed), type specifier = %
Dim i1 As Integer, i2 As Integer, i3 As Integer
'Byte:    1 Byte (unsigned), no type specifier
Dim b1 As Byte, b2 As Byte, b3 As Byte

  l1 = 1024&
  l2 = &H400&
  l3 = &O2000&
  Debug.Assert l1 = l2
  Debug.Assert l2 = l3

  i1 = 1024
  i2 = &H400
  i3 = &O2000
  Debug.Assert i1 = i2
  Debug.Assert i2 = i3

  b1 = 255
  b2 = &O377
  b3 = &HFF
  Debug.Assert b1 = b2
  Debug.Assert b2 = b3

End Sub


var a = 255
var b = 0xff
var c = 0255 // not an octal literal
var d = 2.55e2
System.print([a, b, c, d])


code CrLf=9, IntOut=11;
def A=123, B=$123, C=%11_0011, D=^A;
[IntOut(0, A);  CrLf(0);        \decimal
 IntOut(0, B);  CrLf(0);        \hex
 IntOut(0, C);  CrLf(0);        \binary
 IntOut(0, D);  CrLf(0);        \ASCII
]


byte &55       ;hexadecimal 55
byte $42       ;hexadecimal 42
byte 33        ;decimal 33
byte %00001111 ;binary equivalent of &0F


// 64-bit floating point literals:
2.3
0.3e+34

// single precision (32-bit) floating point literals:
2.3s
0.3e+34s


XS4      DC  E'1.23456E-4'       short floating-point

XDPI     DC  D'3.141592653589793' long floating-point
XD1      DC  D'0'                 long floating-point
XD2      DC  D'1'                 long floating-point
XD3      DC  D'-1'                long floating-point
XD4      DC  D'1.2345E-4'         long floating-point

XQPI     DC  L'3.14159265358979323846264338327950' extended

* short    floating-point -  32 bits -  4 bytes :  6 decimal digits
* long     floating-point -  64 bits -  8 bytes : 16 decimal digits
* extended floating-point - 128 bits - 16 bytes : 33 decimal digits

* absolute approximate range: 5e-79 to 7e75


3.14
5.0
8r      # without the "r"(eal) suffix, "8" would be an integer
.125


# floating point literals are called REAL denotations in Algol 68      #
# They have the following forms:                                       #
#     1: a digit sequence followed by "." followed by a digit sequence #
#     2: a "." followed by a digit sequence                            #
#     3: forms 1 or 2 followed by "e" followed by an optional sign     #
#                     followed by a digit sequence                     #
#     4: a digit sequence follows by "e" followed by an optional sign  #
#                     followed by a digit sequence                     #
#                                                                      #
# The "e" indicates the following optionally-signed digit sequence is  #
# the exponent of the literal.                                         #
# If the implementation allows, a "times ten to the power symbol"      #
# can be used to replace "e" - e.g. a subscript "10" character         #
#                                                                      #
# spaces can appear anywhere in the denotation                         #
# Examples:                                                            #
REAL r;
r := 1.234;
r :=  .987;
r := 4.2e-9;
r := .4e+23;
r := 1e10;
r := 3.142e-23;
r := 1 234 567 .      9           e -                  4;


begin
    real r; long real lr;
    % floating point literals have the following forms:                      %
    %    1 - a digit sequence followed by "." followed by a digit sequence   %
    %    2 - a digit sequence followed by "."                                %
    %    3 - "." followed by a digit sequence                                %
    %    4 - one of the above, followed by "'" followed by an optional sign  %
    %        folloed by a digit sequence                                     %
    % the literal can be followed by "L", indicating it is long real         %
    % the literal can be followed by "I", indicating it is imaginary         %
    % the literal can be followed by "LI" or "IL" indicating it is a long    %
    % imaginary number                                                       %
    % an integer literal ( digit sequence ) can also be used where a         %
    % floating point literal is required                                     %
    % non-imaginary examples:                                                %
    r  := 1.23;
    r  := 1.;
    r  := .9;
    r  := 1.23'5;
    r  := 1.'+4;
    r  := .9'-12;
    r  := 7;
    lr := 5.4321L;
end.


      REM Floating-point literal syntax:
      REM  [-]{digit}[.]{digit}[E[-]{digit}]

      REM Examples:
      PRINT -123.456E-1
      PRINT 1000.0
      PRINT 1E-5

      REM Valid but non-standard examples:
      PRINT 67.
      PRINT 8.9E
      PRINT .33E-
      PRINT -.


double d = 1;
d = 1d;
d = 1D;
d = 1.2; //double is the default if there's no suffix
d = 1.2d; //The suffix is redundant here
d = .2;
d = 12e-12;
d = 12E-12;
d = 1_234e-1_2; //digit separators are allowed since C# 7
float f = 1;
f = 1f;
f = 1F;
f = 1.2f;
f = .2f;
f = 12e-12f;
f = 12E-12f;
f = 1_234e-1_2f;
decimal m = 1;
m = 1m;
m = 1m;
m = 1.2m;
m = .2m;
m = 12e-12m;
m = 12E-12m;
m = 1_234e-1_2m;


#include <iostream>

int main()
{
  // a numeric literal with decimal point is a double
  auto double1 = 2.5;

  // an 'f' of 'F' suffix means the literal is a flaot
  auto float1 = 2.5f;

  // an 'l' or 'L' suffix means a long double
  auto longdouble1 = 2.5l;

  // a number after an 'e' or 'E' is the base 10 exponent
  auto double2 = 2.5e-3;
  auto float2 = 2.5e3f;

  // a '0x' prefix means the literal is hexadecimal. the 'p' is base 2 the exponent
  auto double3 = 0x1p4;
  auto float3 = 0xbeefp-8f;

  std::cout << "\ndouble1: " << double1;
  std::cout << "\nfloat1: " << float1;
  std::cout << "\nlongdouble1: " << longdouble1;
  std::cout << "\ndouble2: " << double2;
  std::cout << "\nfloat2: " << float2;
  std::cout << "\ndouble3: " << double3;
  std::cout << "\nfloat3: " << float3;
  std::cout << "\n";
}


float = [ sign ], { decimal-digit }, decimal-point, decimal-digit, { decimal-digit }, [exponent]
      | [ sign ], decimal-digit, { decimal-digit }, [ decimal-point, { decimal-digit } ], exponent ;
exponent = exponent-marker, [ sign ], decimal-digit, { decimal-digit } ;
sign = "+" | "-" ;
decimal-point = "." ;
decimal-digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
exponent-marker = "e" | "E" | "s" | "S" | "d" | "D" | "f" | "F" | "l" | "L" ;


3.14           ! basic float
+3.14          ! Optional signs
-3.14
10e5           ! exponents signified by e or E
10E+5          ! with optional signs
+10e-5
1.             ! equivalent to 1.0
.5             ! equivalent to 0.5
1/2.           ! floating point approximation of a ratio (0.5)
1/3.           ! 0.3333333333333333
1/0.           ! positive infinity
-1/0.          ! negative infinity
0/0.           ! not-a-number
               ! hexadecimal, octal, and binary float literals are supported.
               ! they require a base 2 exponent expressed as a decimal
               ! preceded by p or P.
0x1.0p3        ! 8.0
-0x1.0P-3      ! -0.125
0b1.010001p3   ! 10.125
0o1.21p3       ! 10.125
               ! comma separators are allowed
1,234.123,456  ! 1234.123456

! normalized hex form ±0x1.MMMMMMMMMMMMMp±EEEE allows any floating-point
! number to be specified precisely according to IEEE 754 representation
+0x1.1234567891234p+0002   ! 4.28444444440952


;;Numeric literals with a decimal component are treated as floating point.
3.14159           ;3.14159

;;An exponent can be specified via "e" or "E" and is always floating point.
2.3456e7          ;23456000.0

;;Hexadecimal literals are supported, including exponents via "p" or "P".
0x1234.abcd       ;4660.6710968018
0x1234.56p3       ;37282.6875

;;Underscores can optionally be used to split numbers into readable chunks.
123_456.789       ;123456.789
0x1234_5678.9a    ;305419896.60156


Convertible string := <significand><exponent>

<significand> := [<sign>]<digits>[.<digits0>]
<exponent>    := E[<sign>]<digits0>
<sign>        := { + | - }
<digits>      := <digit><digits0>
<digits0>     := <digit>*
<digit>       := { 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 }


' FB 1.05.0 Win64 (default dialect)

Dim a As Double = 123.456
Dim b As Double = -123.0
Dim c As Double = -123.0d
Dim d As Double = -123e
Dim e As Double = 743.1e+13
Dim f As Double = 743.1D-13
Dim g As Double = 743.1E13
Dim h As Single = 743D!    Rem ! overrides D
Dim i As Single = 3.1!
Dim j As Single = -123.456e-7f
Dim k As Double = 0#
Dim l As Double = 3.141592653589e3#


println 1.00f    // float (IEEE-32)
println 1.00d    // double (IEEE-64)
println 1.00     // BigDecimal (scaled BigInteger)
println 1.00g    // BigDecimal
println 1.00e0   // BigDecimal

assert 1.00f  instanceof Float
assert 1.00d  instanceof Double
assert 1.00   instanceof BigDecimal
assert 1.00g  instanceof BigDecimal
assert 1.00e0 instanceof BigDecimal


numeric-constant ::= number-constant | number-constant whitespace numeric-constant
whitespace ::= whitespacecharacter | whitespacecharacter whitespace
whitespacecharacter ::= ' ' | TAB
TAB is ascii 9
number-constant ::= arbitrary-constant | arbitrary-constant base-token base-constant
base-token ::= 'b' | 'b-'
base-constant ::= base-digits | base-digits '.' base-digits
base-digits ::= base-digit | base-digit base-digits
base-digit ::= digit | alpha1 | alpha2
alpha1 ::= 'a'|'b'|'c'|'d'|'e'|'f'|'g'|'h'|'i'|'j'|'k'|'l'|'m'
alpha2 ::= 'n'|'o'|'p'|'q'|'r'|'s'|'t'|'u'|'v'|'w'|'x'|'y'|'z'
arbitrary-constant ::= complex-constant | pi-constant | euler-constant | extended-constant
pi-constant ::= complex-constant 'p' complex-constant
euler-constant ::= complex-constant 'x' complex-constant
extended-constant ::= signed-digits 'x' | signed-digits 'r' signed-digits
complex-constant ::= exponential-constant | exponential-constant complex-token exponential-constant
complex-token ::= 'ad' | 'ar' | 'j'
exponential-constant ::= signed-constant | signed-constant 'e' signed-constant
signed-constant ::= decimal-constant | '_' decimal-constant
decimal-constant ::= digits | digits '.' digits
signed-digits ::= digits | '_' digits
digits ::= digit | digit digits
digit ::= '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'


0.1
.1
1.
1e-1    # scientific notation
1e+10
1e-10
0x01p-1 # hex float


val d: Double = 1.0
val d2: Double = 1.234e-10
val f: Float = 728832f
val f2: Float = 728832F


put 0.23
-- 0.2300

-- activate higher printing precision
the floatPrecision = 8

put -.23
-- -0.23000000

put 9.00719925474099e15
-- 9.00719925474099e15

-- result is NOT a float
put 2/3
-- 0

-- casting integer to float
put float(2)/3
-- 0.66666667

-- casting string to float
put float("0.23")
-- 0.23000000


Def ExpType$(x)=Type$(x)
Print ExpType$(-12)="Double", -12
Print ExpType$(12.)="Double", 12.
Print ExpType$(12.e-5)="Double", 12.e-5
Print ExpType$(.1)="Double", .1
Print ExpType$(-12~)="Single", -12~
Print ExpType$(12.~)="Single", 12.~
Print ExpType$(12.e-5~)="Single", 12.e-5~
Print ExpType$(.1~)="Single", .1~


> 123.456; # decimal notation
                                123.456

> 1.23456e2; # scientific notation
                                123.456

> Float( 23, -2 ); # float constructor notation, by mantissa and exponent
                                  0.23

> Float( .123456, 3 ); # again
                                123.456

> Float( 1.23456, 2 ); # again
                                123.456

> Float( 12.3456, 1 ); # again
                                123.456

> HFloat( 1.23456, 2 ); # hardware float constructor
                            123.456000000000

> HFloat( 123.456 ); # again
                            123.456000000000

> 2.3^30; # large floats are printed using scientific notation
                                          11
                           0.7109434879 10

> 2/3; # NOT a float!
                                  2/3

> evalf( 2/3 ); # but you can get one
                              0.6666666667

> 0.0; # zero
                                   0.

> -0.0; # negative zero
                                  -0.

> Float(infinity); # positive infinity
                            Float(infinity)

> Float(-infinity); # minus infinity
                            Float(-infinity)

> Float(undefined); # "NaN", not-a-number
                            Float(undefined)


These numbers are given in the default output format. Large numbers are given in scientific notation.
{6.7^-4,6.7^6,6.7^8}
{0.00049625,90458.4,4.06068*10^6}

This gives all numbers in scientific notation.
ScientificForm[%]
{4.9625*10^(-4),9.04584*10^(4),4.06068*10^(6)}

This gives the numbers in engineering notation, with exponents arranged to be multiples of three.
EngineeringForm[%]
{496.25*10^(-6),90.4584*10^(3),4.06068*10^(6)}

In accounting form, negative numbers are given in parentheses, and scientific notation is never used.
AccountingForm[{5.6,-6.7,10.^7}]
{5.6,(6.7),10000000.}


/* Maxima has machine floating point (usually double precision IEEE 754), and
arbitrary length "big floats" */

/* Here are ordinary floats */
3.14159
2.718e0
1.2345d10
1.2345e10
1.2345f10

/* And big floats (always with a "b" for the exponent) */
3.14159b0
2.718b0
1.2345b10

/* Before computing with big float, one must set precision to some value (default is 16 decimal digits) */
fpprec: 40$

bfloat(%pi);
3.141592653589793238462643383279502884197b0


3.14f                                   // float literal
3.14d, 3.14                             // double literal
3.14m                                   // decimal literal


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

numeric digits 40 -- make lots of space for big numbers
numeric form scientific -- set output form for exponential notation

say 'Sample using objects of type "Rexx" (default):'
fv =      1.5; say      '1.5'.right(20) '==' normalize(fv).right(20) --            1.5
fv =     -1.5; say     '-1.5'.right(20) '==' normalize(fv).right(20) --           -1.5
fv =    15e-1; say    '15e-1'.right(20) '==' normalize(fv).right(20) --            1.5
fv =    3e-12; say    '3e-12'.right(20) '==' normalize(fv).right(20) --          3E-12
fv =    3e+12; say    '3e+12'.right(20) '==' normalize(fv).right(20) --  3000000000000
fv = 17.3E-12; say '17.3E-12'.right(20) '==' normalize(fv).right(20) --       1.73E-11
fv = 17.3E+12; say '17.3E+12'.right(20) '==' normalize(fv).right(20) -- 17300000000000
fv = 17.3E+40; say '17.3E+40'.right(20) '==' normalize(fv).right(20) --       1.73E+41
fv = 0.033e+9; say '0.033e+9'.right(20) '==' normalize(fv).right(20) --       33000000
fv = 0.033e-9; say '0.033e-9'.right(20) '==' normalize(fv).right(20) --        3.3E-11
say

say 'Sample using primitive type "float":'
ff = float
ff = float    15e-1; say    '15e-1'.right(20) '==' normalize(ff).right(20) --            1.5
ff = float 17.3E-12; say '17.3E-12'.right(20) '==' normalize(ff).right(20) --       1.73E-11
ff = float 17.3E+12; say '17.3E+12'.right(20) '==' normalize(ff).right(20) -- 17300000000000
ff = float 0.033E+9; say '0.033E+9'.right(20) '==' normalize(ff).right(20) --       33000000
ff = float 0.033E-9; say '0.033E-9'.right(20) '==' normalize(ff).right(20) --        3.3E-11
say

say 'Sample using primitive type "double":'
fd = double
fd =    15e-1; say    '15e-1'.right(20) '==' normalize(fd).right(20) --            1.5
fd = 17.3E-12; say '17.3E-12'.right(20) '==' normalize(fd).right(20) --       1.73E-11
fd = 17.3E+12; say '17.3E+12'.right(20) '==' normalize(fd).right(20) -- 17300000000000
fd = 17.3E+40; say '17.3E+40'.right(20) '==' normalize(fd).right(20) --       1.73E+41
fd = 0.033E+9; say '0.033E+9'.right(20) '==' normalize(fd).right(20) --       33000000
fd = 0.033E-9; say '0.033E-9'.right(20) '==' normalize(fd).right(20) --        3.3E-11
say

return

/**
 * Convert input to a Rexx object and add zero to the value which forces NetRexx to change its internal representation
 *
 * @param fv a Rexx object containing the floating point value
 * @return a Rexx object which allows NetRexx string manipulation methods to act on it
 */
method normalize(fv) private constant
  return fv + 0


2.0                % normal float. Must have a decimal after the decimal point
-2.1
2.01E3             % exponent can be E of e
2.01e3
2.01E-3
2.01e-3
1_000_123.123_456  % underscores can be used for clarity


1.2345e-4      decimal floating-point
7e5            decimal floating-point
1.234_567_89e0 decimal floating-point.
1.0s0          decimal floating-point (single precision)
1.0d0          decimal floating-point (double precision)
1.34q0         decimal floating-point (quadruple/extended precision)

111.0101e7b    binary floating-point equals 111.0101 * 2**7
                                     or 7.3125 * 2**7
1e5b           binary floating-point equals 1 * 2**5


FLOAT
    :   '.' DIGITS (Exponent)?
    |   DIGITS '.' Exponent
    |   DIGITS ('.' (DIGITS (Exponent)?)? | Exponent)
    ;

DIGITS : ( '0' .. '9' )+ ;

Exponent
    :    ('e' | 'E') ( '+' | '-' )? DIGITS
    ;


#lang racket
.2
2.
2.+0i  ; zero imaginary part
2e0
#x10.8 ; hex float
#o1e2  ; oct float
2.0f0  ; single float
1.0t0  ; extended 80-bit float (when available on platform)


something = 127
something = '127'     /*exactly the same as the above. */
something = 1.27e2
something = 1.27E2
something = 1.27E+2
something = '    +    0001.27e+00000000000000002     '


2.3         // Normal floating point literal
3.          // Equivalent to 3.0 (3 would be interpreted as an integer)
2f64        // The type (in this case f64, a 64-bit floating point number) may be appended to the value
1_000.2_f32 // Underscores may appear anywhere in the number for clarity.


1. //Double equal to 1.0
1.0 //Double, a 64-bit IEEE-754 floating point number (equivalent to Java's double primitive type)
2432311.7567374 //Double
1.234E-10 //Double
1.234e-10 //Double
758832d //Double
728832f //32-bit IEEE-754 floating point number (equivalent to Java's float primitive type)
1.0f //Float
758832D //Double
728832F //Float
1.0F //Float
1 / 2. //Double
1 / 2 //Int equal to 0

// Constants
Float.MinPositiveValue
Float.NaN
Float.PositiveInfinity
Float.NegativeInfinity

Double.MinPositiveValue
Double.NaN
Double.PositiveInfinity
Double.NegativeInfinity


.2      ; 0.2
2.      ; 2.0
2e3     ; 2000
2.+3.i  ; complex floating-point number

; in Scheme, floating-point numbers are inexact numbers
(inexact? 2.)
; #t
(inexact? 2)
; #f


let double = 1.0 as Double  // Double precision
let float = 1.0 as Float // Single precision
let scientific = 1.0E-12

// Swift does not feature type coercion for explicit type declaration
let sum = double + float // Error

let div = 1.1 / 2 // Double
let div1 = 1 / 2 // 0


F logic(a, b)
   print(‘a and b: ’(a & b))
   print(‘a or b: ’(a | b))
   print(‘not a: ’(!a))


 Op-codes
                     Or    And   Xor
                     ---   ---   ---
 Memory to memory    OC    NC    XC
 Memory to register  O     N     X
 Immediate           OI    NI    XI


LDA myBoolean
BNE isTrue
;code that would execute if myBoolean is false, goes here.
RTS
isTrue:
;code that would execute if myBoolean is true, goes here.
RTS


(defun logical-ops (a b)
   (progn$ (cw "(and a b) = ~x0~%" (and a b))
           (cw "(or a b)  = ~x0~%" (or a b))
           (cw "(not a) =   ~x0~%" (not a))))


BYTE FUNC Not(BYTE a)
  IF a=0 THEN
    RETURN (1)
  FI
RETURN (0)

PROC Main()
  BYTE a,b,res

  FOR a=0 TO 1
  DO
    FOR b=0 TO 1
    DO
      res=a AND b
      PrintF("%B AND %B=%B",a,b,res)
      res=a OR b
      PrintF("|%B OR %B=%B",a,b,res)
      res=a ! b
      PrintF("|%B XOR %B=%B",a,b,res)
      res=Not(a)
      PrintF("|NOT %B=%B%E",a,res)
    OD
  OD
RETURN


procedure Print_Logic(A : Boolean; B : Boolean) is
begin
   Put_Line("A and B is " & Boolean'Image(A and B));
   Put_Line("A or B  is " & Boolean'Image(A or B));
   Put_Line("A xor B is " & Boolean'Image(A xor B));
   Put_Line("not A   is " & Boolean'Image(not A));
end Print_Logic;


module AndOrNot where

open import Data.Bool
open import Data.Product

test : Bool → Bool → Bool × Bool × Bool
test x y = x ∧ y , x ∨ y , not x


function logic(a,b) {
  println("a AND b: " + (a && b))
  println("a OR b: " + (a || b))
  println("NOT a: " + (!a))
}


void
out(integer a, integer b)
{
    o_integer(a && b);
    o_byte('\n');
    o_integer(a || b);
    o_byte('\n');
    o_integer(!a);
    o_byte('\n');
}


PROC print_logic = (BOOL a, b)VOID:
(
# for a 6-7 bit/byte compiler #
  printf(($"a and b is "gl$, a AND b);
  printf(($"a or b is "gl$, a OR b);
  printf(($"not a is "gl$, NOT a);
  printf(($"a equivalent to b is "gl$, a EQ b);
  printf(($"a not equivalent to b is "gl$, a NE b);

# Alternatively ASCII #
  printf(($"a and b is "gl$, a & b);
  printf(($"a and b is "gl$, a /\ b);  <!-- http://web.archive.org/web/20021207211127/http://www.bobbemer.com/BRACES.HTM -->
  printf(($"a or b is "gl$, a \/ b);
  printf(($"a equivalent to b "gl$, a = b);
  printf(($"a not equivalent to b "gl$, a /= b);

¢ for a European 8 bit/byte charcter set eg. ALCOR or GOST ¢
  printf(($"a and b is "gl$, a ∧ b);
  printf(($"a or b is "gl$, a ∨ b);
  printf(($"not a is "gl$, ¬ a)
  printf(($"a not equivalent to b is "gl$, a ≠ b)
)


procedure booleanOperations( logical value a, b ) ;
    begin

        % algol W has the usual "and", "or" and "not" operators         %
        write( a,      " and ", b, ": ", a and   b );
        write( a,      "  or ", b, ": ", a  or   b );
        write( "         not ", a, ": ",   not   a );

        % logical values can be compared with the = and not = operators %
        %     a not = b can be used for a xor b                         %
        write( a,      " xor ", b, ": ", a not = b );
        write( a,      " equ ", b, ": ", a     = b );

    end booleanOperations ;


#include <hopper.h>

main:
  a=0, b=1  // a and b have some values...

  {"values A=",a,", B=",b} println

  {"AND : ",a,b} and, println
  {"OR  : ",a,b} or, println
  {"XOR : ",a,b} xor, println
  {"NAND: ",a,b} nand, println
  {"NOR : ",a,b} nor, println
  {"NOT A: ",a}not, println
  {"NOT B: ",b}not, println

  x=-1,{3,3} rand array(x), mulby(10),ceil,gthan(5),mov(x)
  y=-1,{3,3} rand array(y), mulby(10),ceil,gthan(5),mov(y)

  {"\nArrays\nX:\n",x,"\nY:\n",y}println

  {"AND :\n",x,y} and, println
  {"OR  :\n",x,y} or, println
  {"XOR :\n",x,y} xor, println
  {"NAND:\n",x,y} nand, println
  {"NOR :\n",x,y} nor, println
  {"NOT X :\n",x} not, println
  {"NOT Y :\n",y} not, println

exit(0)


boolean a = true;
boolean b = false;
System.Debug('a AND b: ' + (a && b));
System.Debug('a OR b: ' + (a || b));
System.Debug('NOT a: ' + (!a));
System.Debug('a XOR b: ' + (a ^ b));


LOGICALOPS←{(⍺∧⍵)(⍺∨⍵)(~⍺)(⍺⍲⍵)(⍺⍱⍵)(⍺≠⍵)}


/* ARM assembly Raspberry PI  */
/*  program logicoper.s   */
/* Constantes    */
.equ STDOUT, 1
.equ WRITE,  4
.equ EXIT,   1
/* Initialized data */
.data
szMessResultAnd:   .asciz "Result of And : \n"
szMessResultOr:    .asciz "Result of Or : \n"
szMessResultEor:   .asciz "Result of Exclusive Or : \n"
szMessResultNot:   .asciz "Result of Not : \n"
szMessResultClear: .asciz "Result of Bit Clear : \n"

sMessAffBin: .ascii "Register value : "
sZoneBin:    .space 36,' '
             .asciz "\n"

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

    mov r0,#0b1100      @ binary value 1
    mov r1,#0b0110      @ binary value 2
    bl logicfunc

100:   @ standard end of the program
    mov r0,#0                   @ return code
    pop {fp,lr}                 @ restore 2 registers
    mov r7,#EXIT                @ request to exit program
    swi 0                       @ perform the system call

/******************************************************************/
/*     logics functions                              */
/******************************************************************/
/* r0 contains the first value */
/* r1 contains the second value */
logicfunc:
    push {r2,lr}                     @ save  registers
    mov r2,r0                        @ save value 1 in r2
    ldr r0,iAdrszMessResultAnd       @ and
    bl affichageMess
    mov r0,r2                        @ load value 1 in r0
    and r0,r1
    bl affichage2
    ldr r0,iAdrszMessResultOr        @ or
    bl affichageMess
    mov r0,r2
    orr r0,r1
    bl affichage2
    ldr r0,iAdrszMessResultEor       @ exclusive or
    bl affichageMess
    mov r0,r2
    eor r0,r1
    bl affichage2
    ldr r0,iAdrszMessResultNot       @ not
    bl affichageMess
    mov r0,r2
    mvn r0,r1
    bl affichage2
    ldr r0,iAdrszMessResultClear     @ bit clear
    bl affichageMess
    mov r0,r2
    bic r0,r1
    bl affichage2
100:
    pop {r2,lr}                      @ restore registers
    bx lr
iAdrszMessResultAnd:    .int szMessResultAnd
iAdrszMessResultOr:     .int szMessResultOr
iAdrszMessResultEor:    .int szMessResultEor
iAdrszMessResultNot:    .int szMessResultNot
iAdrszMessResultClear:  .int szMessResultClear
/******************************************************************/
/*     register display in binary                              */
/******************************************************************/
/* r0 contains the register */
affichage2:
    push {r0,lr}     /* save registers */
    push {r1-r5}     /* save other registers */
    mrs r5,cpsr      /* saves state register in r5 */
    ldr r1,iAdrsZoneBin
    mov r2,#0         @ read bit position counter
    mov r3,#0         @ position counter of the written character
1:                @ loop
    lsls r0,#1        @ left shift  with flags
    movcc r4,#48      @ flag carry off   character '0'
    movcs r4,#49      @ flag carry on    character '1'
    strb r4,[r1,r3]   @ character ->   display zone
    add r2,r2,#1      @ + 1 read bit position counter
    add r3,r3,#1      @ + 1 position counter of the written character
    cmp r2,#8         @ 8 bits read
    addeq r3,r3,#1    @ + 1 position counter of the written character
    cmp r2,#16        @ etc
    addeq r3,r3,#1
    cmp r2,#24
    addeq r3,r3,#1
    cmp r2,#31        @ 32 bits shifted ?
    ble 1b            @ no -> loop

    ldr r0,iAdrsZoneMessBin    @ address of message result
    bl affichageMess           @ display result

100:
    msr cpsr,r5    /* restore state register */
    pop {r1-r5}    /* restore other registers */
    pop {r0,lr}
    bx lr
iAdrsZoneBin: .int sZoneBin
iAdrsZoneMessBin: .int sMessAffBin

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save registers */
    push {r0,r1,r2,r7}    		/* save others registers */
    mov r2,#0   				/* counter length */
1:      	            /* loop length calculation */
    ldrb r1,[r0,r2]  			/* read byte start position + index */
    cmp r1,#0       			/* if 0 it's over */
    addne r2,r2,#1   			/* else add 1 to 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 */
    mov r7,#WRITE               /* "write" system call */
    swi #0                      /* system call */
    pop {r0,r1,r2,r7}     		/* restore other registers */
    pop {fp,lr}    				/* restore 2 registers */
    bx lr	        			/* return */


logic: function [a b][
	print ["a AND b =" and? a b]
	print ["a OR b =" or? a b]
	print ["NOT a = " not? a]
]

logic true false


bool a = true;
bool b = false;

write(a & b);
write(a && b);  //(with conditional evaluation of right-hand argument)
write(a | b);
write(a || b);  //(with conditional evaluation of right-hand argument)
write(a ^ b);
write(!a);


a = 1
b = 0
msgbox % "a and b is " . (a && b)
msgbox % "a or b is " . (a || b)
msgbox % "not a is " . (!a)


Method "logic ops_,_" is
[
    a : boolean;
    b : boolean;
|
    Print: "not a: " ++ “¬a”;
    Print: "not b: " ++ “¬b”;
    Print: "a and b: " ++ “a ∧ b”;
    Print: "a or b: " ++ “a ∨ b”;
    Print: "a nand b: " ++ “a ↑ b”;
    Print: "a nor b: " ++ “a ↓ b”;
    Print: "a implies b: " ++ “a → b”; // = not a OR b
    Print: "a is implied b b: " ++ “a ← b”; // = a OR not b
    Print: "a does not imply b: " ++ “a ↛ b”; // = a AND not b
    Print: "a is not implied by b: " ++ “a ↚ b”; // not a AND b
    Print: "a xor b: " ++ “a ⊕ b”; // equivalent to a ≠ b
    Print: "a biconditional b: " ++ “a ↔ b”; // equivalent to a = b
];


Lbl LOGIC
r₁→A
r₂→B
Disp "AND:",(A?B)▶Dec,i
Disp "OR:",(A??B)▶Dec,i
Disp "NOT:",(A?0,1)▶Dec,i
Return


10 A = -1
20 B = 0
30 PRINT A AND B
40 PRINT A OR B
50 PRINT (A AND (NOT B)) OR ((NOT A) AND B)
60 PRINT NOT A


/* The following three functions assume 0 is false and 1 is true */

/* And */
define a(x, y) {
    return(x * y)
}

/* Or */
define o(x, y) {
    return(x + y - x * y)
}

/* Not */
define n(x) {
    return(1 - x)
}

define f(a, b) {
    "a and b: "
    a(a, b)
    "a or b: "
    o(a, b)
    "not a: "
    n(a)
}


logic = { a, b |
  p "a and b: #{ a && b }"
  p "a or b: #{ a || b }"
  p "not a: #{ not a }"
}


void print_logic(int a, int b)
{
  printf("a and b is %d\n", a && b);
  printf("a or b is %d\n", a || b);
  printf("not a is %d\n", !a);
}


using System;

namespace LogicalOperations
{
    class Program
    {
        static void Main(string[] args)
        {
            bool a = true, b = false;
            Console.WriteLine("a and b is {0}", a && b);
            Console.WriteLine("a or b is {0}", a || b);
            Console.WriteLine("Not a is {0}", !a);
            Console.WriteLine("a exclusive-or b is {0}", a ^ b);
        }
    }
}


void print_logic(bool a, bool b)
{
  std::cout << std::boolalpha; // so that bools are written as "true" and "false"
  std::cout << "a and b is " << (a && b) << "\n";
  std::cout << "a or b is " << (a || b) << "\n";
  std::cout << "not a is " << (!a) << "\n";
}


 Function Foo( a, b )
   // a and b was defined as .F. (false) or .T. (true)
   ? a .AND. b
   ? a .OR. b
   ? .NOT. a, .NOT. b
   Return Nil


(defn logical [a b]
  (prn (str "a and b is " (and a b)))
  (prn (str "a or b is " (or a b)))
  (prn (str "not a is "  (not a))))

(logical true false)


       IDENTIFICATION DIVISION.
       PROGRAM-ID. print-logic.

       DATA DIVISION.
       LOCAL-STORAGE SECTION.
       01  result                  PIC 1 USAGE BIT.

       LINKAGE SECTION.
       01  a                       PIC 1 USAGE BIT.
       01  b                       PIC 1 USAGE BIT.

       PROCEDURE DIVISION USING a, b.
           COMPUTE result = a B-AND b
           DISPLAY "a and b is " result

           COMPUTE result = a B-OR b
           DISPLAY "a or b is " result

           COMPUTE result = B-NOT a
           DISPLAY "Not a is " result

           COMPUTE result = a B-XOR b
           DISPLAY "a exclusive-or b is " result

           GOBACK
           .


<cffunction name = "logic" hint = "Performs basic logical operations">
  <cfargument name = "a" required = "yes" type = "boolean" />
  <cfargument name = "a" required = "yes" type = "boolean" />
  <cfoutput>
    'A' AND 'B' is #a AND b#< br />
    'A' OR  'B' is #a OR  b#< br />
    NOT 'A'     is #!a#
  </cfoutput>
</cffunction>


(defun logic (a b)
  (print "a and b is") (write (and a b))
  (print "a or b is" ) (write (or a b))
  (print "not a is"  ) (write (not a)))


import std.stdio;

void logic(T, U)(T lhs, U rhs) {
    writefln("'%s' is of type '%s', '%s' is of type '%s';",
             lhs, typeid(typeof(lhs)), rhs,typeid(typeof(rhs)));
    writefln("\t'%s' AND '%s' is %s, ", lhs, rhs, lhs && rhs);
    writefln("\t'%s' OR '%s' is %s, ", lhs, rhs, lhs || rhs);
    writefln("\tNOT '%s' is %s.\n", lhs, !lhs);
}

class C { int value; }

void main() {
    bool theTruth = true;
    bool theLie = false;
    real zeroReal = 0.0L;
    real NaN; // D initializes floating point values to NaN
    int zeroInt  = 0;
    real[] nullArr = null;
    string emptyStr = "";
    string nullStr = null;
    C someC = new C;
    C nullC = null;

    // Note: Struct is value type in D, but composite
    //  so no default bool equivalent.

    logic(theTruth, theLie);
    logic(zeroReal, NaN);
    logic(zeroInt, nullArr);
    logic(nullStr, emptyStr);
    logic(someC, nullC);
}


[ 1 q ] sT

[ 0=T 0 ] s!
[ l! x [email protected] l! x [email protected] + l! x ] s&
[ l! x [email protected] l! x [email protected] * l! x ] s|

[ 48 + P ] s.

[ Sb Sa
  la l. x [ ] P lb l. x [  ] P
  la lb l& x l. x [   ] P
  la Lb l| x l. x [   ] P
  La l! x l. x
  A P
] sF

[a b a&b a|b !a] P A P
0 0 lF x
0 1 lF x
1 0 lF x
1 1 lF x


program LogicalOperations;

{$APPTYPE CONSOLE}

const
  a = True;
  b = False;
begin
  Write('a = ');
  Writeln(a);
  Write('b = ');
  Writeln(b);
  Writeln;

  Write('a AND b: ');
  Writeln(a AND b);

  Write('a OR b: ');
  Writeln(a OR b);

  Write('NOT a: ');
  Writeln(NOT a);

  Write('a XOR b: ');
  Writeln(a XOR b);
end.


var a := True;
var b := False;

Print('a = ');
PrintLn(a);
Print('b = ');
PrintLn(b);

Print('a AND b: ');
PrintLn(a AND b);

Print('a OR b: ');
PrintLn(a OR b);

Print('NOT a: ');
PrintLn(NOT a);

Print('a XOR b: ');
PrintLn(a XOR b);


var a = true
var b = false
print("a and b is \(a && b)")
print("a or b is \(a || b)")
print("Not a is \(!a)")


showbool a b:
    !.( a b or a b and a b xor a b not a )

for a in [ false true ]:
    for b in [ false true ]:
        showbool a b


def logicalOperations(a :boolean, b :boolean) {
    return ["and" => a & b,
            "or"  => a | b,
            "not" => !a,
            "xor" => a ^ b]
}


func logic a b . .
  if a = 1 and b = 1
    r1 = 1
  .
  if a = 1 or b = 1
    r2 = 1
  .
  if a = 0
    r3 = 1
  .
  print r1 & " " & r2 & " " & r3
.
call logic 0 0
call logic 0 1
call logic 1 0
call logic 1 1


LogicalOperations(BOOLEAN A,BOOLEAN B) := FUNCTION
  ANDit := A AND B;
  ORit  := A OR B;
  NOTA  := NOT A;
  XORit := (A OR B) AND NOT (A AND B);
  DS    := DATASET([{A,B,'A AND B is:',ANDit},
                    {A,B,'A OR B is:',ORit},
                    {A,B,'NOT A is:',NOTA},
                    {A,B,'A XOR B is:',XORit}],
                    {BOOLEAN AVal,BOOLEAN BVal,STRING11 valuetype,BOOLEAN val});
  RETURN DS;
END;

LogicalOperations(FALSE,FALSE);
LogicalOperations(FALSE,TRUE);
LogicalOperations(TRUE,FALSE);
LogicalOperations(TRUE,TRUE);
LogicalOperations(1>2,1=1); //Boolean expressions are also valid here


compare_bool = fn (A, B) {
    io.format("~p and ~p = ~p~n", [A, B, A and B])
    io.format("~p or ~p = ~p~n", [A, B, A or B])
    io.format("not ~p = ~p~n", [A, not A])
    io.format("~p xor ~p = ~p~n", [A, B, A xor B])
    io.format("~n")
}

@public
run = fn () {
    compare_bool(true, true)
    compare_bool(true, false)
    compare_bool(false, true)
    compare_bool(false, false)
}


import extensions;

public program()
{
    bool a := true;
    bool b := false;

    console.printLine("a and b is ", a && b);
    console.printLine("a or b is ", a || b);
    console.printLine("Not a is ", a.Inverted);
    console.printLine("a xor b is ", a ^^ b)
}


iex(1)> true and false
false
iex(2)> false or true
true
iex(3)> not false
true


--Open cmd and elm-repl and directly functions can be created

--Creating Functions
t=True
f=False
opand a b= a && b
opor a b= a || b
opnot a= not a

--Using the created Functions
opand t f
opor t f
opnot f

--Output will be False, True and True of type Boolean!
--end


1> true and false.
false
2> false or true.
true
3> true xor false.
true
4> not false.
true
5> not (true and true).
false


procedure print_logic(integer a, integer b)
    printf(1,"a and b is %d\n", a and b)
    printf(1,"a or b is %d\n", a or b)
    printf(1,"a xor b is %d\n", a xor b)
    printf(1,"not a is %d\n", not a)
end procedure


=CONCATENATE($A1, " AND ", $B1, " is ", AND($A1,$B1))


let printLogic a b =
    printfn "a and b is %b" (a && b)
    printfn "a or b is %b" (a || b)
    printfn "Not a is %b" (not a)
    // The not-equals operator has the same effect as XOR on booleans.
    printfn "a exclusive-or b is %b" (a <> b)


: logical-operators ( a b -- )
    {
        [ "xor is: " write xor . ]
        [ "and is: " write and . ]
        [ "or is:  " write or . ]
        [ "not is: " write drop not . ]
    } 2cleave ;


class Main
{
  static Void doOps (Bool arg1, Bool arg2)
  {
    echo ("$arg1 and $arg2 = ${arg1.and(arg2)}")
    echo ("$arg1 or $arg2 = ${arg1.or(arg2)}")
    echo ("not $arg1 = ${arg1.not}")
    echo ("$arg1 xor $arg2 = ${arg1.xor(arg2)}")
  }

  public static Void main ()
  {
    [true,false].each |Bool arg1|
    {
      [true,false].each |Bool arg2|
      {
        doOps (arg1, arg2)
      }
    }
  }
}


: .bool ( ? -- ) if ." true" else ." false" then ;
: logic ( a b -- ) 0<> swap 0<> swap
 cr ." a = " over .bool ."   b = " dup .bool
 cr ." a and b = " 2dup and .bool
 cr ." a  or b = " over  or .bool
 cr ." not a = " 0= .bool ;


       SUBROUTINE PRNLOG(A, B)
       LOGICAL A, B
       PRINT *, 'a and b is ', A .AND. B
       PRINT *, 'a or b is ', A .OR. B
       PRINT *, 'not a is ', .NOT. A

C       You did not ask, but the following logical operators are also standard
C       since ANSI FORTRAN 66
C       =======================================================================

C       This yields the same results as .EQ., but has lower operator precedence
C       and only works with LOGICAL operands:
       PRINT *, 'a equivalent to b is ', A .EQV. B

C       This yields the same results as .NE., but has lower operator precedence
C       and only works with LOGICAL operands (this operation is also commonly
C       called "exclusive or"):
       PRINT *, 'a not equivalent to b is ', A .NEQV. B
       END


def logical( a, b ) = println( """
a and b   = ${a and b}
a or b    = ${a or b}
not a     = ${not a}
a xor b   = ${a xor b}
""" )

for i <- [false, true], j <- [false, true] do logical( i, j )


window 1, @"Logical Operations", (0,0,480,270)

Boolean a, b

text ,,,,, 43

print @"In FB, the Boolean constants _true or YES = 1, _false or NO = 0"
print fn StringByPaddingToLength( @"", 39, @"-", 0 )

print @"a\tb\tand\tor\txor\tnand\tnor"
print fn StringByPaddingToLength( @"", 39, @"-", 0 )

a = NO  : b = NO  : print a, b, a and b, a or  b, a xor b, a nand b, a nor b
a = NO  : b = YES : print a, b, a and b, a or  b, a xor b, a nand b, a nor b
a = YES : b = NO  : print a, b, a and b, a or  b, a xor b, a nand b, a nor b
a = YES : b = YES : print a, b, a and b, a or  b, a xor b, a nand b, a nor b

print

print "FB also has shorthand operator expressions"
print fn StringByPaddingToLength( @"", 39, @"-", 0 )
print @"a\tb\t&&\t||\t^^\t^&\t^|"
print fn StringByPaddingToLength( @"", 39, @"-", 0 )

a = NO  : b = NO  : print a, b, a && b, a ||  b, a ^^ b, a ^& b, a ^| b
a = NO  : b = YES : print a, b, a && b, a ||  b, a ^^ b, a ^& b, a ^| b
a = YES : b = NO  : print a, b, a && b, a ||  b, a ^^ b, a ^& b, a ^| b
a = YES : b = YES : print a, b, a && b, a ||  b, a ^^ b, a ^& b, a ^| b

HandleEvents


Logical := function(a, b)
    return [ a or b, a and b, not a ];
end;

Logical(true, true);
# [ true, true, false ]

Logical(true, false);
# [ true, false, false ]

Logical(false, true);
# [ true, false, true ]

Logical(false, false);
# [ false, false, true ]


[indent=4]
/*
   Logical operations in Genie
   valac logicals.gs
   ./logicals true false
*/

def logicals(a:bool, b:bool)
    print @"$a and $b is $(a and b)"
    print @"$a or $b is $(a or b)"
    print @"not $a is $(not a)"

init
    a:bool = bool.parse(args[1])
    b:bool = bool.parse(args[2])
    logicals(a, b)


func printLogic(a, b bool) {
    fmt.Println("a and b is", a && b)
    fmt.Println("a or b is", a || b)
    fmt.Println("not a is", !a)
}


PROCEDURE Foo( a, b )
   // a and b was defined as .F. (false) or .T. (true)
   ? a .AND. b
   ? a .OR. b
   ? ! a, ! b
   RETURN


a = False
b = True

a_and_b = a && b
a_or_b  = a || b
not_a   = not a
a_xor_b  = a /= b
a_nxor_b = a == b
a_implies_b = a <= b -- sic!


fun logic a b
  println "a and b = " + (a && b)
  println "a or  b = " + (a || b)
  println "  not a = " + (!a)
endfun


  x     = value1 /= 0
  y     = value2 /= 0
  NOTx  = x == 0
  xANDy = x * y
  xORy  = x + y  /= 0
  EOR   = x /= y


U0 PrintLogic(Bool a, Bool b) {
  Print("a and b is %d\n", a && b);
  Print("a or b is %d\n", a || b);
  Print("not a is %d\n", !a);
}

PrintLogic(TRUE, FALSE);


(defn logic [a b]
  (print "a and b:" (and a b))
  (print "a or b:" (or a b))
  (print "not a:" (not a)))


invocable all

procedure main()                      #: sample demonstrating boolean function use

limit := 4
char2 := char(2)||char(0)
every (i := char(1 to limit)|char2) do {
   write(iop := "bnot","( ",image(i)," ) = ",image(iop(i)))
   every k := 3 | 10 do {
     write("bistrue(",image(i),",",k,") - ", if bistrue(i,k) then "returns" else "fails")
     write("bisfalse(",image(i),",",k,") - ", if bisfalse(i,k) then "returns" else "fails")
     }
   every (j := char(1 to limit)) & (iop := "bor"|"band"|"bxor") do
      write(iop,"( ",image(i),", ",image(j)," ) = ",image(iop(i,j)))
   }
end

procedure bisfalse(b,p)                #: test if bit p (numbered right to left from 1) is false; return b or fails
return boolean_testbit(0,b,p)
end

procedure bistrue(b,p)                 #: test if bit p is true; return b or fails
return boolean_testbit(1,b,p)
end

procedure bnot(b)                      #: logical complement of b (not is a reserved word)
static cs,sc
initial sc := reverse(cs := string(&cset))
if type(b) ~== "string" then runerr(103,b)
return map(b,cs,sc)                    # en-mass inversion through remapping ordered cset
end

procedure bor(b1,b2)                   #: logical or
return boolean_op(ior,b1,b2)
end

procedure band(b1,b2)                  #: logical or
return boolean_op(iand,b1,b2)
end

procedure bxor(b1,b2)                  #: logical or
return boolean_op(ixor,b1,b2)
end

procedure boolean_testbit(v,b,p)       #: (internal) test if bit p is true/false; return b or fail
if not 0 <= integer(p) = p then runerr(101,p)
if type(b) ~== "string" then runerr(103,b)
if v = ishift(ord(b[-p/8-1]), -(p%8)+1) then return b
end

procedure boolean_op(iop,b1,b2)        #: boolean helper
local b3,i
static z
initial z := char(0)
if type(b1) ~== "string" then runerr(103,b1)
if type(b2) ~== "string" then runerr(103,b2)
b3 := ""
every i := -1 to -max(*b1,*b2) by -1 do
   b3 :=  char(iop(ord(b1[i]|z),ord(b2[i]|z))) || b3
return b3
end


printLogic := method(a,b,
  writeln("a and b is ", a and b)
  writeln("a or b is ", a or b)
  writeln("not a is ", a not)
)


public static void logic(boolean a, boolean b){
  System.out.println("a AND b: " + (a && b));
  System.out.println("a OR b: " + (a || b));
  System.out.println("NOT a: " + (!a));
}


function logic(a,b) {
  print("a AND b: " + (a && b));
  print("a OR b: " + (a || b));
  print("NOT a: " + (!a));
}


def logic(a; b):
  "\(a) and \(b) => \(a and b)",
  "\(a) or \(b)  => \(a or  b)",
  "\(a) | not    => \(a | not)",
  "if \(a) then true else false end => \(if a then true else false end)" ;


using Printf

function exerciselogic(a::Bool, b::Bool)
    st = @sprintf " %5s" a
    st *= @sprintf " %5s" b
    st *= @sprintf " %5s" ~a
    st *= @sprintf " %5s" a | b
    st *= @sprintf " %5s" a & b
    st *= @sprintf " %5s" a $ b
end

println("Julia's logical operations on Bool:")
println("   a     b    not   or    and   xor")
for a in [true, false], b in [true, false]
    println(exerciselogic(a, b))
end


// version 1.0.6

fun logicalDemo(b1: Boolean, b2: Boolean) {
    println("b1             =  $b1")
    println("b2             =  $b2")
    println("b1 and b2      =  ${b1 and b2}")
    println("b1 or b2       =  ${b1 or b2}")
    println("b1 xor b2      =  ${b1 xor b2}")
    println("not b1         =  ${!b1}")
    println("b1 && b2       =  ${b1 && b2}")
    println("b1 || b2       =  ${b1 || b2}")
    println()
}

fun main(args: Array<String>) {
    logicalDemo(true, true)
    logicalDemo(true, false)
    logicalDemo(false, false)
    logicalDemo(false, true)
}


{and true true true false true}  -> false
{or  true true true false true}  -> true
{not true}                       -> false


// br is just for formatting output here
define br => '\r'

// define vars
local(a = true, b = false)

// boolean comparators.
// note, not including comparison operators which would return boolean results
'a AND b: ' + (#a && #b)
br
'a OR b: ' + (#a || #b)
br
'NOT a: ' + !#a
br
'NOT a (using not): ' + not #a


False =0
True  =not( False)

print " True ="; True, "False ="; False, "NB True here shown as -1"
print

print " a   b    AND  OR   XOR"
a =0: b =0: print " "; a; "   "; b; "     "; a and b; "    "; a or  b; "    "; a xor b
a =0: b =1: print " "; a; "   "; b; "     "; a and b; "    "; a or  b; "    "; a xor b
a =1: b =0: print " "; a; "   "; b; "     "; a and b; "    "; a or  b; "    "; a xor b
a =1: b =1: print " "; a; "   "; b; "     "; a and b; "    "; a or  b; "    "; a xor b

end