#include <iomanip>
#include <iostream>
#include <vector>

constexpr int MU_MAX = 1'000'000;
std::vector<int> MU;

int mobiusFunction(int n) {
    if (!MU.empty()) {
        return MU[n];
    }

    // Populate array
    MU.resize(MU_MAX + 1, 1);
    int root = sqrt(MU_MAX);

    for (int i = 2; i <= root; i++) {
        if (MU[i] == 1) {
            // for each factor found, swap + and -
            for (int j = i; j <= MU_MAX; j += i) {
                MU[j] *= -i;
            }
            // square factor = 0
            for (int j = i * i; j <= MU_MAX; j += i * i) {
                MU[j] = 0;
            }
        }
    }

    for (int i = 2; i <= MU_MAX; i++) {
        if (MU[i] == i) {
            MU[i] = 1;
        } else if (MU[i] == -i) {
            MU[i] = -1;
        } else if (MU[i] < 0) {
            MU[i] = 1;
        } else if (MU[i] > 0) {
            MU[i] = -1;
        }
    }

    return MU[n];
}

int main() {
    std::cout << "First 199 terms of the möbius function are as follows:\n    ";
    for (int n = 1; n < 200; n++) {
        std::cout << std::setw(2) << mobiusFunction(n) << "  ";
        if ((n + 1) % 20 == 0) {
            std::cout << '\n';
        }
    }

    return 0;
}


import std.math;
import std.stdio;

immutable MU_MAX = 1_000_000;

int mobiusFunction(int n) {
    static initialized = false;
    static int[MU_MAX + 1] MU;

    if (initialized) {
        return MU[n];
    }

    // populate array
    MU[] = 1;
    int root = cast(int) sqrt(cast(real) MU_MAX);

    for (int i = 2; i <= root; i++) {
        if (MU[i] == 1) {
            // for each factor found, swap + and -
            for (int j = i; j <= MU_MAX; j += i) {
                MU[j] *= -i;
            }
            // square factor = 0
            for (int j = i * i; j <= MU_MAX; j += i * i) {
                MU[j] = 0;
            }
        }
    }

    for (int i = 2; i <= MU_MAX; i++) {
        if (MU[i] == i) {
            MU[i] = 1;
        } else if (MU[i] == -i) {
            MU[i] = -1;
        } else if (MU[i] < 0) {
            MU[i] = 1;
        } else if (MU[i] > 0) {
            MU[i] = -1;
        }
    }

    initialized = true;
    return MU[n];
}

void main() {
    writeln("First 199 terms of the möbius function are as follows:");
    write("    ");
    for (int n = 1; n < 200; n++) {
        writef("%2d  ", mobiusFunction(n));
        if ((n + 1) % 20 == 0) {
            writeln;
        }
    }
}


// Möbius function. Nigel Galloway: January 31st., 2021
let fN g=let n=primes32()
         let rec fN i g e l=match (l/g,l%g,e) with (1,0,false)->i
                                                  |(n,0,false)->fN (0-i) g true n
                                                  |(_,0,true) ->0
                                                  |_          ->fN i (Seq.head n) false l
         fN -1 (Seq.head n) false g
let mobius=seq{yield 1; yield! Seq.initInfinite((+)2>>fN)}
mobius|>Seq.take 500|>Seq.chunkBySize 25|>Seq.iter(fun n->Array.iter(printf "%3d") n;printfn "")


USING: formatting grouping io math.extras math.ranges sequences ;

"First 199 terms of the Möbius sequence:" print
199 [1,b] [ mobius ] map " " prefix 20 group
[ [ "%3s" printf ] each nl ] each


program moebius
    use iso_fortran_env, only: output_unit

    integer, parameter          :: mu_max=1000000, line_break=20
    integer, parameter          :: sqroot=int(sqrt(real(mu_max)))
    integer                     :: i, j
    integer, dimension(mu_max)  :: mu

    mu = 1

    do i = 2, sqroot
        if (mu(i) == 1) then
            do j = i, mu_max, i
                mu(j) = mu(j) * (-i)
            end do

            do j = i**2, mu_max, i**2
                mu(j) = 0
            end do
        end if
    end do

    do i = 2, mu_max
        if (mu(i) == i) then
            mu(i) = 1
        else if (mu(i) == -i) then
            mu(i) = -1
        else if (mu(i) < 0) then
            mu(i) = 1
        else if (mu(i) > 0) then
            mu(i) = -1
        end if
    end do

    write(output_unit,*) "The first 199 terms of the Möbius sequence are:"
    write(output_unit,'(3x)', advance="no") ! Alignment of first number
    do i = 1, 199
        write(output_unit,'(I2,x)', advance="no") mu(i)
        if (modulo(i+1, line_break) == 0) write(output_unit,*)
    end do
end program moebius


function mobius( n as uinteger ) as integer
    if n = 1 then return 1
    for d as uinteger = 2 to int(sqr(n))
        if n mod d = 0 then
            if n mod (d*d) = 0 then return 0
            return -mobius(n/d)
        end if
    next d
    return -1
end function

dim as string outstr = " .     "
for i as uinteger = 1 to 200
    if mobius(i)>=0 then outstr += " "
    outstr += str(mobius(i))+"     "
    if i mod 10 = 9 then
        print outstr
        outstr = ""
    end if
next i


local fn IsPrime( n as long ) as Boolean
  Boolean i, result

  if ( n < 2 ) then result = NO : exit fn

  for i = 2 to n + 1
    if ( i * i <= n ) and ( n mod i == 0 )
      result = NO : exit fn
    end if
  next
  result = YES
end fn = result

local fn Mobius( n as long ) as long
  long i, p = 0, result = 0

  if ( n == 1 ) then result = 1 : exit fn

  for i = 1 to n + 1
    if ( n mod i == 0 ) and ( fn IsPrime( i ) == YES )
      if ( n mod ( i * i ) == 0 )
        result = 0 : exit fn
      else
        p++
      end if
    end if
  next

  if( p mod 2 != 0 )
    result = -1
  else
    result = 1
  end if
end fn = result

window 1, @"Möbius function", (0,0,600,300)

printf @"First 100 terms of Mobius sequence:"

long i
for i = 1 to 100
  printf @"%2ld\t", fn Mobius(i)
  if ( i mod 20 == 0 ) then print
next

HandleEvents


package main

import "fmt"

func möbius(to int) []int {
    if to < 1 {
        to = 1
    }
    mobs := make([]int, to+1) // all zero by default
    primes := []int{2}
    for i := 1; i <= to; i++ {
        j := i
        cp := 0      // counts prime factors
        spf := false // true if there is a square prime factor
        for _, p := range primes {
            if p > j {
                break
            }
            if j%p == 0 {
                j /= p
                cp++
            }
            if j%p == 0 {
                spf = true
                break
            }
        }
        if cp == 0 && i > 2 {
            cp = 1
            primes = append(primes, i)
        }
        if !spf {
            if cp%2 == 0 {
                mobs[i] = 1
            } else {
                mobs[i] = -1
            }
        }
    }
    return mobs
}

func main() {
    mobs := möbius(199)
    fmt.Println("Möbius sequence - First 199 terms:")
    for i := 0; i < 200; i++ {
        if i == 0 {
            fmt.Print("    ")
            continue
        }
        if i%20 == 0 {
            fmt.Println()
        }
        fmt.Printf("  % d", mobs[i])
    }
}


10 FOR T = 0 TO 9
20 FOR U = 1 TO 10
30 N = 10*T + U
40 GOSUB 100
50 PRINT USING "##  ";M;
60 NEXT U
70 PRINT
80 NEXT T
90 END
100 IF N = 1 THEN M = 1 : RETURN
110 M = 1 : F = 2
120 IF N MOD (F*F) = 0 THEN M = 0 : RETURN
130 IF N MOD F = 0 THEN GOSUB 170
140 F = F + 1
150 IF F <= N THEN GOTO 120
160 RETURN
170 M = -M
180 N = N/F
190 RETURN


import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Data.Vector.Unboxed (toList)
import Math.NumberTheory.ArithmeticFunctions.Moebius (Moebius(..),
                                                      sieveBlockMoebius)
import System.Environment (getArgs, getProgName)
import System.IO (hPutStrLn, stderr)
import Text.Read (readMaybe)

-- Calculate the Möbius function, μ(n), for a sequence of values starting at 1.
moebiusBlock :: Word -> [Moebius]
moebiusBlock = toList . sieveBlockMoebius 1

showMoebiusBlock :: Word -> [Moebius] -> String
showMoebiusBlock cols = intercalate "\n" . map (concatMap showMoebius) .
                        chunksOf (fromIntegral cols)
  where showMoebius MoebiusN = " -1"
        showMoebius MoebiusZ = "  0"
        showMoebius MoebiusP = "  1"

main :: IO ()
main = do
  prog <- getProgName
  args <- map readMaybe <$> getArgs
  case args of
    [Just cols, Just n] ->
      putStrLn ("μ(n) for 1 ≤ n ≤ " ++ show n ++ ":\n") >>
      putStrLn (showMoebiusBlock cols $ moebiusBlock n)
    _ -> hPutStrLn stderr $ "Usage: " ++ prog ++ " num-columns maximum-number"


public class MöbiusFunction {

    public static void main(String[] args) {
        System.out.printf("First 199 terms of the möbius function are as follows:%n    ");
        for ( int n = 1 ; n < 200 ; n++ ) {
            System.out.printf("%2d  ", möbiusFunction(n));
            if ( (n+1) % 20 == 0 ) {
                System.out.printf("%n");
            }
        }
    }

    private static int MU_MAX = 1_000_000;
    private static int[] MU = null;

    //  Compute mobius function via sieve
    private static int möbiusFunction(int n) {
        if ( MU != null ) {
            return MU[n];
        }

        //  Populate array
        MU = new int[MU_MAX+1];
        int sqrt = (int) Math.sqrt(MU_MAX);
        for ( int i = 0 ; i < MU_MAX ; i++ ) {
            MU[i] = 1;
        }

        for ( int i = 2 ; i <= sqrt ; i++ ) {
            if ( MU[i] == 1 ) {
                //  for each factor found, swap + and -
                for ( int j = i ; j <= MU_MAX ; j += i ) {
                    MU[j] *= -i;
                }
                //  square factor = 0
                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {
                    MU[j] = 0;
                }
            }
        }

        for ( int i = 2 ; i <= MU_MAX ; i++ ) {
            if ( MU[i] == i ) {
                MU[i] = 1;
            }
            else if ( MU[i] == -i ) {
                MU[i] = -1;
            }
            else if ( MU[i] < 0 ) {
                MU[i] = 1;
            }
            else if ( MU[i] > 0 ) {
                MU[i] = -1;
            }
        }
        return MU[n];
    }

}


# Input: a non-negative integer, $n
# Output: an array of size $n + 1 such that the nth-mobius number is .[$n]
# i.e. $n|mobius_array[-1]
# For example, the first mobius number could be evaluated by 1|mobius_array[-1].
def mobius_array:
  . as $n
  | ($n|sqrt) as $sqrt
  | reduce range(2; 1 + $sqrt) as $i ([range(0; $n + 1) | 1];
       if .[$i] == 1
       then # for each factor found, swap + and -
         reduce range($i; $n + 1; $i) as $j (.; .[$j] *= -$i)
         | ($i*$i) as $isq #  square factor = 0
         | reduce range($isq; $n + 1; $isq) as $j (.; .[$j] = 0 )
       else .
       end )
  | reduce range(2; 1 + $n) as $i (.;
       if   .[$i] ==  $i then .[$i] = 1
       elif .[$i] == -$i then .[$i] = -1
       elif .[$i]  <   0 then .[$i] = 1
       elif .[$i]  >   0 then .[$i] = -1
       else .[$i] = 0                   # avoid "-0"
       end);

# For one-off computations:
def mu($n): $n | mobius_array[-1];


using Primes

# modified from reinermartin's PR at https://github.com/JuliaMath/Primes.jl/pull/70/files
function moebius(n::Integer)
    @assert n > 0
    m(p, e) = p == 0 ? 0 : e == 1 ? -1 : 0
    reduce(*, m(p, e) for (p, e) in factor(n) if p ≥ 0; init=1)
end
μ(n) = moebius(n)

print("First 199 terms of the Möbius sequence:\n   ")
for n in 1:199
    print(lpad(μ(n), 3), n % 20 == 19 ? "\n" : "")
end


import kotlin.math.sqrt

fun main() {
    println("First 199 terms of the möbius function are as follows:")
    print("    ")
    for (n in 1..199) {
        print("%2d  ".format(mobiusFunction(n)))
        if ((n + 1) % 20 == 0) {
            println()
        }
    }
}

private const val MU_MAX = 1000000
private var MU: IntArray? = null

//  Compute mobius function via sieve
private fun mobiusFunction(n: Int): Int {
    if (MU != null) {
        return MU!![n]
    }

    //  Populate array
    MU = IntArray(MU_MAX + 1)
    val sqrt = sqrt(MU_MAX.toDouble()).toInt()
    for (i in 0 until MU_MAX) {
        MU!![i] = 1
    }
    for (i in 2..sqrt) {
        if (MU!![i] == 1) {
            //  for each factor found, swap + and -
            for (j in i..MU_MAX step i) {
                MU!![j] *= -i
            }
            //  square factor = 0
            for (j in i * i..MU_MAX step i * i) {
                MU!![j] = 0
            }
        }
    }
    for (i in 2..MU_MAX) {
        when {
            MU!![i] == i -> {
                MU!![i] = 1
            }
            MU!![i] == -i -> {
                MU!![i] = -1
            }
            MU!![i] < 0 -> {
                MU!![i] = 1
            }
            MU!![i] > 0 -> {
                MU!![i] = -1
            }
        }
    }
    return MU!![n]
}


function buildArray(size, value)
    local tbl = {}
    for i=1, size do
        table.insert(tbl, value)
    end
    return tbl
end

MU_MAX = 1000000
sqroot = math.sqrt(MU_MAX)
mu = buildArray(MU_MAX, 1)

for i=2, sqroot do
    if mu[i] == 1 then
        -- for each factor found, swap + and -
        for j=i, MU_MAX, i do
            mu[j] = mu[j] * -i
        end
        -- square factor = 0
        for j=i*i, MU_MAX, i*i do
            mu[j] = 0
        end
    end
end

for i=2, MU_MAX do
    if mu[i] == i then
        mu[i] = 1
    elseif mu[i] == -i then
        mu[i] = -1
    elseif mu[i] < 0 then
        mu[i] = 1
    elseif mu[i] > 0 then
        mu[i] = -1
    end
end

print("First 199 terms of the mobius function are as follows:")
io.write("    ")
for i=1, 199 do
    io.write(string.format("%2d  ", mu[i]))
    if (i + 1) % 20 == 0 then
        print()
    end
end


import std/[math, sequtils, strformat]

func getStep(n: int): int {.inline.} =
  result = 1 + n shl 2 - n shr 1 shl 1

func primeFac(n: int): seq[int] =
  var
    maxq = int(sqrt(float(n)))
    d = 1
    q: int = 2 + (n and 1)   # Start with 2 or 3 according to oddity.

  while q <= maxq and n %% q != 0:
    q = getStep(d)
    inc d
  if q <= maxq:
    let q1 = primeFac(n /% q)
    let q2 = primeFac(q)
    result = concat(q2, q1, result)
  else:
    result.add(n)

func squareFree(num: int): bool =
  let fact = primeFac num

  for i in fact:
    if fact.count(i) > 1:
      return false

  return true

func mobius(num: int): int =
  if num == 1: return num

  let fact = primeFac num

  for i in fact:
    ## check if it has a squared prime factor
    if fact.count(i) == 2:
      return 0

  if num.squareFree:
    if fact.len mod 2 == 0:
      return 1
    else:
      return -1

when isMainModule:
  echo "The first 199 möbius numbers are:"

  for i in 1..199:
    stdout.write fmt"{mobius(i):4}"
    if i mod 20 == 0:
      echo "" # print newline


use utf8;
use strict;
use warnings;
use feature 'say';
use List::Util 'uniq';

sub prime_factors {
    my ($n, $d, @factors) = (shift, 1);
    while ($n > 1 and $d++) {
        $n /= $d, push @factors, $d until $n % $d;
    }
    @factors
}

sub μ {
    my @p = prime_factors(shift);
    @p == uniq(@p) ? 0 == @p%2 ? 1 : -1 : 0;
}

my @möebius;
push @möebius, μ($_) for 1 .. (my $upto = 199);

say "Möbius sequence - First $upto terms:\n" .
    (' 'x4 . sprintf "@{['%4d' x $upto]}", @möebius) =~ s/((.){80})/$1\n/gr;


with javascript_semantics
function Moebius(integer n)
    if n=1 then return 1 end if
    sequence f = prime_factors(n,true)
    for i=2 to length(f) do
        if f[i] = f[i-1] then return 0 end if
    end for
    return iff(odd(length(f))?-1:+1)
end function

sequence s = {"  ."}
for i=1 to 199 do s = append(s,sprintf("%3d",Moebius(i))) end for
puts(1,join_by(s,1,20," "))


# Python Program to evaluate
# Mobius def M(N) = 1 if N = 1
# M(N) = 0 if any prime factor
# of N is contained twice
# M(N) = (-1)^(no of distinct
# prime factors)
# Python Program to
# evaluate Mobius def
# M(N) = 1 if N = 1
# M(N) = 0 if any
# prime factor of
# N is contained twice
# M(N) = (-1)^(no of
# distinct prime factors)

# def to check if
# n is prime or not
def isPrime(n) :

    if (n < 2) :
        return False
    for i in range(2, n + 1) :
        if (i * i <= n and n % i == 0) :
            return False
    return True

def mobius(N) :

    # Base Case
    if (N == 1) :
        return 1

    # For a prime factor i
    # check if i^2 is also
    # a factor.
    p = 0
    for i in range(1, N + 1) :
        if (N % i == 0 and
                isPrime(i)) :

            # Check if N is
            # divisible by i^2
            if (N % (i * i) == 0) :
                return 0
            else :

                # i occurs only once,
                # increase f
                p = p + 1

    # All prime factors are
    # contained only once
    # Return 1 if p is even
    # else -1
    if(p % 2 != 0) :
        return -1
    else :
        return 1

# Driver Code
print("Mobius numbers from 1..99:")

for i in range(1, 100):
  print(f"{mobius(i):>4}", end = '')

  if i % 20 == 0: print()
# This code is contributed by
# Manish Shaw(manishshaw1)


	org	100h
	jmp	test
	;;; Implementation of F(A).
F:	ana	a	; Zero?
	jz	one	; Then set A=1
	mov	b,a	; Otherwise, set B=A,
	push	b	; And put it on the stack
	dcr	a	; Set A=A-1
	call	F	; Set A=F(A-1)
	call	M 	; Set A=M(F(A-1))
	pop	b	; Retrieve input value
	cma		; (-A)+B is actually one cycle faster
	inr	a	; than C=A;A=B;A-=B, and equivalent
	add	b
	ret
one:	mvi	a,1	; Set A to 1,
	ret		; and return.
	;;; Implementation of M(A).
M:	ana	a	; Zero?
	rz		; Then keep it that way and return.
	mov	b,a
	push	b	; Otherwise, same deal as in F,
	dcr	a	; but M and F are called in opposite
	call	M 	; order.
	call	F
	pop	b
	cma
	inr	a
	add	b
	ret
	;;; Demonstration code.
test:	lhld	6	; Set stack pointer to highest usable
	sphl		; memory.
	;;; Print F([0..15])
	lxi	d,fpfx	; Print "F: "
	mvi 	c,9
	call	5
	xra	a	; Start with N=0
floop:	push	psw	; Keep N
	call	F	; Get value for F(N)
	call	pdgt	; Print it
	pop	psw	; Restore N
	inr 	a	; Next N
	cpi	16	; Done yet?
	jnz	floop
	;;; Print M([0..15])
	lxi	d,mpfx	; Print "\r\nM: "
	mvi	c,9
	call	5
	xra	a	; Start with N=0
mloop:	push	psw	; same deal as above
	call	M
	call	pdgt
	pop	psw	; Restore N
	inr	a
	cpi	16
	jnz	mloop
	rst	0	; Explicit exit, we got rid of system stack
	;;; Print digit and space
pdgt:	adi	'0'	; ASCII
	mov	e,a
	mvi	c,2
	call	5
	mvi	e,' '	; Space
	mvi	c,2
	jmp	5	; Tail call optimization
fpfx:	db	'F: $'
mpfx:	db	13,10,'M: $'


use Prime::Factor;

sub μ (Int \n) {
    return 0 if n %% 4 or n %% 9 or n %% 25 or n %% 49 or n %% 121;
    my @p = prime-factors(n);
    +@p == +@p.unique ?? +@p %% 2 ?? 1 !! -1 !! 0
}

my @möbius = lazy flat '', 1, (2..*).hyper.map: -> \n { μ(n) };

# The Task
put "Möbius sequence - First 199 terms:\n",
    @möbius[^200]».fmt('%3s').batch(20).join: "\n";


/*REXX pgm computes & shows a value grid of the Möbius function for a range of integers.*/
parse arg LO HI grp .                            /*obtain optional arguments from the CL*/
if  LO=='' |  LO==","  then  LO=   0             /*Not specified?  Then use the default.*/
if  HI=='' |  HI==","  then  HI= 199             /* "      "         "   "   "     "    */
if grp=='' | grp==","  then grp=  20             /* "      "         "   "   "     "    */
                                                 /*                            ______   */
call genP HI                                     /*generate primes up to the  √  HI     */
say center(' The Möbius sequence from ' LO " ──► " HI" ", max(50, grp*3), '═')   /*title*/
$=                                               /*variable holds output grid of GRP #s.*/
    do j=LO  to  HI;  $= $  right( mobius(j), 2) /*process some numbers from  LO ──► HI.*/
    if words($)==grp  then do;  say substr($, 2);  $=    /*show grid if fully populated,*/
                           end                           /*  and nullify it for more #s.*/
    end   /*j*/                                  /*for small grids, using wordCnt is OK.*/

if $\==''  then say substr($, 2)                 /*handle any residual numbers not shown*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
mobius: procedure expose @.;  parse arg x        /*obtain a integer to be tested for mu.*/
        if x<1  then return '∙'                  /*special? Then return symbol for null.*/
        #= 0                                     /*start with a value of zero.          */
             do k=1;  p= @.k                     /*get the  Kth  (pre─generated)  prime.*/
             if p>x  then leave                  /*prime (P)   > X?    Then we're done. */
             if p*p>x  then do;   #= #+1;  leave /*prime (P**2 > X?    Bump # and leave.*/
                            end
             if x//p==0  then do; #= #+1         /*X divisible by P?   Bump mu number.  */
                                  x= x % p       /*                    Divide by prime. */
                                  if x//p==0  then return 0  /*X÷by P?  Then return zero*/
                              end
             end   /*k*/                         /*#  (below) is almost always small, <9*/
        if #//2==0  then return  1               /*Is # even?   Then return postive  1  */
                         return -1               /* " "  odd?     "     "   negative 1. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6= 13;  nP=6  /*assign low primes; # primes.*/
                    do lim=nP  until lim*lim>=HI /*only keep primes up to the  sqrt(HI).*/
                    end   /*lim*/
       do [email protected].nP+4  by 2  to HI                  /*only find odd primes from here on.   */
       parse var j '' -1 _;if _==5  then iterate /*Is last digit a "5"?   Then not prime*/
       if j// 3==0  then iterate                 /*is J divisible by  3?    "   "    "  */
       if j// 7==0  then iterate                 /* " "     "      "  7?    "   "    "  */
       if j//11==0  then iterate                 /* " "     "      " 11?    "   "    "  */
       if j//13==0  then iterate                 /* " "     "      " 13?    "   "    "  */
                 do k=7  while k*k<=j            /*divide by some generated odd primes. */
                 if j // @.k==0  then iterate j  /*Is J divisible by  P?  Then not prime*/
                 end   /*k*/                     /* [↓]  a prime  (J)  has been found.  */
       nP= nP+1;    if nP<=HI  then @.nP= j      /*bump prime count; assign prime to  @.*/
       end      /*j*/;              return


report z_mutual_recursion.

class hoffstadter_sequences definition.
  public section.
    class-methods:
      f
        importing
          n             type int4
        returning
          value(result) type int4,

      m
        importing
          n             type int4
        returning
          value(result) type int4.
endclass.

class hoffstadter_sequences implementation.
  method f.
    result = cond int4(
      when n eq 0
      then 1
      else n - m( f( n - 1 ) ) ).
  endmethod.

  method m.
    result = cond int4(
      when n eq 0
      then 0
      else n - f( m( n - 1 ) ) ).
  endmethod.
endclass.

start-of-selection.
  write: |{ reduce string(
    init results = |f(0 - 19): { hoffstadter_sequences=>f( 0 ) }|
    for i = 1 while i < 20
    next results = |{ results }, { hoffstadter_sequences=>f( i ) }| ) }|, /.

  write: |{ reduce string(
    init results = |m(0 - 19): { hoffstadter_sequences=>m( 0 ) }|
    for i = 1 while i < 20
    next results = |{ results }, { hoffstadter_sequences=>m( i ) }| ) }|, /.


mobStr = "      . "

for i = 1 to 200
    if mobius(i) >= 0
       mobStr + = " "
    ok
    temp = string(mobius(i))
    if left(temp,2) = "-0"
       temp = right(temp,len(temp)-1)
    ok
    mobStr += temp + " "
    if i % 10 = 9
        see mobStr + nl
        mobStr = "     "
    ok
next

func mobius(n)
     if n = 1
        return 1
     ok
     for d = 2 to ceil(sqrt(n))
         if n % d = 0
            if n % (d*d) = 0
               return 0
            ok
            return -mobius(n/d)
         ok
     next
     return -1


require 'prime'

def μ(n)
  pd = n.prime_division
  return 0 unless pd.map(&:last).all?(1)
  pd.size.even? ? 1 : -1
end

(["  "] + (1..199).map{|n|"%2s" % μ(n)}).each_slice(20){|line| puts line.join(" ") }


say moebius(53)    #=> -1
say moebius(54)    #=> 0
say moebius(55)    #=> 1


    PRINT "Enter an integer"
    INPUT N
    IF N < 0 THEN LET N = -N
    IF N < 2 THEN GOTO 100 + N
    LET C = 1
    LET F = 2
 10 IF ((N/F)/F)*F*F = N THEN GOTO 100
    IF (N/F)*F = N THEN GOTO 30
 20 LET F = F + 1
    IF F<=N THEN GOTO 10
    GOTO 100 + C
 30 LET N = N / F
    LET C = -C
    GOTO 20
 99 PRINT "-1"
    END
100 PRINT "0"
    END
101 PRINT "1"
    END


import "/fmt" for Fmt
import "/math" for Int

var isSquareFree = Fn.new { |n|
    var i = 2
    while (i * i <= n) {
        if (n%(i*i) == 0) return false
        i = (i > 2) ? i + 2 : i + 1
    }
    return true
}

var mu = Fn.new { |n|
    if (n < 1) Fiber.abort("Argument must be a positive integer")
    if (n == 1) return 1
    var sqFree = isSquareFree.call(n)
    var factors = Int.primeFactors(n)
    if (sqFree && factors.count % 2 == 0) return 1
    if (sqFree) return -1
    return 0
}

System.print("The first 199 Möbius numbers are:")
for (i in 0..9) {
    for (j in 0..19) {
        if (i == 0 && j == 0) {
            System.write("    ")
        } else {
            System.write("%(Fmt.dm(3, mu.call(i*20 + j))) ")
        }
    }
    System.print()
}


(mutual-recursion
 (defun f (n)
    (declare (xargs :mode :program))
    (if (zp n)
        1
        (- n (m (f (1- n))))))

 (defun m (n)
    (declare (xargs :mode :program))
    (if (zp n)
        0
        (- n (f (m (1- n)))))))


with Ada.Text_Io; use Ada.Text_Io;
procedure Mutual_Recursion is
   function M(N : Integer) return Integer;
   function F(N : Integer) return Integer is
   begin
      if N = 0 then
         return 1;
      else
         return N - M(F(N - 1));
      end if;
   end F;
   function M(N : Integer) return Integer is
   begin
      if N = 0 then
         return 0;
      else
         return N - F(M(N-1));
      end if;
   end M;
begin
   for I in 0..19 loop
      Put_Line(Integer'Image(F(I)));
   end loop;
   New_Line;
   for I in 0..19 loop
      Put_Line(Integer'Image(M(I)));
   end loop;
end Mutual_recursion;


func Mobius(N);
int  N, Cnt, F, K;
[Cnt:= 0;
F:= 2;  K:= 0;
repeat  if rem(N/F) = 0 then
                [Cnt:= Cnt+1;
                N:= N/F;
                K:= K+1;
                if K >= 2 then return 0;
                ]
        else    [F:= F+1;  K:= 0];
until   F > N;
return if Cnt&1 then -1 else 1;
];

int  N;
[Format(3, 0);
Text(0, "   ");
for N:= 1 to 199 do
        [RlOut(0, float(Mobius(N)));
        if rem(N/20) = 19 then CrLf(0);
        ];
]


outstr$ = " .  "
for i = 1 to 200
    if mobius(i) >= 0 then outstr$ = outstr$ + " " : fi
    outstr$ = outstr$ + str$(mobius(i)) + "  "
    if mod(i, 10) = 9 then
        print outstr$
        outstr$ = ""
    end if
next i
end

sub mobius(n)
    if n = 1 then return 1 : fi
    for d = 2 to int(sqr(n))
        if mod(n, d) = 0 then
            if mod(n, (d*d)) = 0 then return 0 : fi
            return -mobius(n/d)
        end if
    next d
    return -1
end sub


fcn mobius(n){
   pf:=primeFactors(n);
   sq:=pf.filter1('wrap(f){ (n % (f*f))==0 });  // False if square free
   if(sq==False){ if(pf.len().isEven) 1 else -1 }
   else 0
}
fcn primeFactors(n){  // Return a list of prime factors of n
   acc:=fcn(n,k,acc,maxD){  // k is 2,3,5,7,9,... not optimum
      if(n==1 or k>maxD) acc.close();
      else{
	 q,r:=n.divr(k);   // divr-->(quotient,remainder)
	 if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt()));
	 return(self.fcn(n,k+1+k.isOdd,acc,maxD))  # both are tail recursion
      }
   }(n,2,Sink(List),n.toFloat().sqrt());
   m:=acc.reduce('*,1);      // mulitply factors
   if(n!=m) acc.append(n/m); // opps, missed last factor
   else acc;
}


integer F(integer n);
integer M(integer n);

integer F(integer n)
{
    integer r;
    if (n) {
	r = n - M(F(n - 1));
    } else {
	r = 1;
    }
    return r;
}

integer M(integer n)
{
    integer r;
    if (n) {
	r = n - F(M(n - 1));
    } else {
	r = 0;
    }
    return r;
}

integer main(void)
{
    integer i;
    i = 0;
    while (i < 20) {
	o_winteger(3, F(i));
	i += 1;
    }
    o_byte('\n');
    i = 0;
    while (i < 20) {
	o_winteger(3, M(i));
	i += 1;
    }
    o_byte('\n');
    return 0;
}


PROC (INT)INT m; # ONLY required for ELLA ALGOL 68RS - an official subset OF full ALGOL 68 #

PROC f = (INT n)INT:
  IF n = 0 THEN 1
  ELSE n - m(f(n-1)) FI;

m := (INT n)INT:
  IF n = 0 THEN 0
  ELSE n - f(m(n-1)) FI;

main:
(
  FOR i FROM 0 TO 19 DO
    print(whole(f(i),-3))
  OD;
  new line(stand out);
  FOR i FROM 0 TO 19 DO
    print(whole(m(i),-3))
  OD;
  new line(stand out)
)


begin
    % define mutually recursive funtions F and M that compute the elements   %
    % of the Hofstadter Female and Male sequences                            %

    integer procedure F ( integer value n ) ;
        if n = 0 then 1 else n - M( F( n - 1 ) );

    integer procedure M ( integer value n ) ;
        if n = 0 then 0 else n - F( M( n - 1 ) );

    % print the first few elements of the sequences                          %
    i_w := 2; s_w := 1; % set I/O formatting                                 %
    write( "F: " );
    for i := 0 until 20 do writeon( F( i ) );
    write( "M: " );
    for i := 0 until 20 do writeon( M( i ) );

end.


-- f :: Int -> Int
on f(x)
    if x = 0 then
        1
    else
        x - m(f(x - 1))
    end if
end f

-- m :: Int -> Int
on m(x)
    if x = 0 then
        0
    else
        x - f(m(x - 1))
    end if
end m

-- TEST
on run
    set xs to range(0, 19)

    {map(f, xs), map(m, xs)}
end run

-- GENERIC FUNCTIONS

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to lambda(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property lambda : f
        end script
    end if
end mReturn

-- range :: Int -> Int -> [Int]
on range(m, n)
    if n < m then
        set d to -1
    else
        set d to 1
    end if
    set lst to {}
    repeat with i from m to n by d
        set end of lst to i
    end repeat
    return lst
end range


.text
.global _start
	@@@	Implementation of F(n), n in R0. n is considered unsigned.
F:	tst	r0,r0		@ n = 0?
	moveq	r0,#1		@ In that case, the result is 1
	bxeq	lr		@ And we can return to the caller
	push	{r0,lr}		@ Save link register and argument to stack
	sub	r0,r0,#1	@ r0 -= 1    = n-1
	bl	F		@ r0 = F(r0) = F(n-1)
	bl	M		@ r0 = M(r0) = M(F(n-1))
	pop	{r1,lr}		@ Restore link register and argument in r1
	sub	r0,r1,r0	@ Result is n-F(M(n-1))
	bx	lr		@ Return to caller.

	@@@	Implementation of M(n), n in R0. n is considered unsigned.
M:	tst	r0,r0		@ n = 0?
	bxeq	lr		@ In that case the result is also 0; return.
	push	{r0,lr}		@ Save link register and argument to stack
	sub	r0,r0,#1	@ r0 -= 1    = n-1
	bl	M		@ r0 = M(r0) = M(n-1)
	bl	F		@ r0 = M(r0) = F(M(n-1))
	pop	{r1,lr}		@ Restore link register and argument in r1
	sub	r0,r1,r0	@ Result is n-M(F(n-1))
	bx	lr		@ Return to caller

	@@@	Print F(0..15) and M(0..15)
_start:	ldr	r1,=fmsg	@ Print values for F
	ldr	r4,=F
	bl	prfn
	ldr	r1,=mmsg	@ Print values for M
	ldr	r4,=M
	bl	prfn
	mov	r7,#1		@ Exit process
	swi	#0

	@@@	Helper function for output: print [r1], then [r4](0..15)
	@@@	This assumes [r4] preserves r3 and r4; M and F do.
prfn:	push	{lr}		@ Keep link register
	bl	pstr		@ Print the string
	mov	r3,#0		@ Start at 0
1:	mov	r0,r3		@ Call the function in r4 with current number
	blx	r4
	add	r0,r0,#'0	@ Make ASCII digit
	ldr	r1,=dgt		@ Store in digit string
	strb	r0,[r1]
	ldr	r1,=dstr	@ Print result
	bl	pstr
	add	r3,r3,#1	@ Next number
	cmp	r3,#15		@ Keep going up to and including 15
	bls	1b
	ldr	r1,=nl		@ Print newline afterwards
	bl	pstr
	pop	{pc}		@ Return to address on stack
	@@@	Print length-prefixed string r1 to stdout
pstr:	push	{lr}		@ Keep link register
	mov	r0,#1		@ stdout = 1
	ldrb	r2,[r1],#1	@ r2 = length prefix
	mov	r7,#4		@ 4 = write syscall
	swi	#0
	pop	{pc}		@ Return to address on stack
.data
fmsg:	.ascii	"\3F: "
mmsg:	.ascii	"\3M: "
dstr:	.ascii	"\2"
dgt:	.ascii	"* "
nl:	.ascii 	"\1\n"


Loop 20
   i := A_Index-1, t .= "`n" i "`t   " M(i) "`t     " F(i)
MsgBox x`tmale`tfemale`n%t%

F(n) {
   Return n ? n - M(F(n-1)) : 1
}

M(n) {
   Return n ? n - F(M(n-1)) : 0
}


cat mutual_recursion.awk:
#!/usr/local/bin/gawk -f

# User defined functions
function F(n)
{ return n == 0 ? 1 : n - M(F(n-1)) }

function M(n)
{ return n == 0 ? 0 : n - F(M(n-1)) }

BEGIN {
  for(i=0; i <= 20; i++) {
    printf "%3d ", F(i)
  }
  print ""
  for(i=0; i <= 20; i++) {
    printf "%3d ", M(i)
  }
  print ""
}


' Mutually recursive
FUNCTION F(int n) TYPE int
    RETURN IIF(n = 0, 1, n - M(F(n -1)))
END FUNCTION

FUNCTION M(int n) TYPE int
    RETURN IIF(n = 0, 0, n - F(M(n - 1)))
END FUNCTION

' Get iteration limit, default 20
SPLIT ARGUMENT$ BY " " TO arg$ SIZE args
limit = IIF(args > 1, VAL(arg$[1]), 20)

FOR i = 0 TO limit
    PRINT F(i) FORMAT "%2d "
NEXT
PRINT
FOR i = 0 TO limit
    PRINT M(i) FORMAT "%2d "
NEXT
PRINT


DECLARE FUNCTION f! (n!)
DECLARE FUNCTION m! (n!)

FUNCTION f! (n!)
    IF n = 0 THEN
        f = 1
    ELSE
        f = m(f(n - 1))
    END IF
END FUNCTION

FUNCTION m! (n!)
    IF n = 0 THEN
        m = 0
    ELSE
        m = f(m(n - 1))
    END IF
END FUNCTION


# Rosetta Code problem: http://rosettacode.org/wiki/Mutual_recursion
# by Jjuanhdez, 06/2022

n = 24
print "n : ";
for i = 0 to n : print ljust(i, 3);    : next i
print chr(10); ("-" * 78)
print "F : ";
for i = 0 to n : print ljust(F(i), 3); : next i
print chr(10); "M : ";
for i = 0 to n : print ljust(M(i), 3); : next i
end

function F(n)
    if n = 0 then return 0 else return n - M(F(n-1))
end function

function M(n)
    if n = 0 then return 0 else return n - F(M(n-1))
end function


cat mutual_recursion.bc:
define f(n) {
  if ( n == 0 ) return(1);
  return(n - m(f(n-1)));
}

define m(n) {
  if ( n == 0 ) return(0);
  return(n - f(m(n-1)));
}


get "libhdr"

// Mutually recursive functions
let f(n) = n=0 -> 1, n - m(f(n-1))
and m(n) = n=0 -> 0, n - f(m(n-1))

// Print f(0..15) and m(0..15)
let start() be
$(  writes("F:")
    for i=0 to 15 do
    $(  writes(" ")
        writen(f(i))
    $)
    writes("*NM:")
    for i=0 to 15 do
    $(  writes(" ")
        writen(m(i))
    $)
    writes("*N")
$)


female = null #yes, this is necessary

male = { n |
  true? n == 0
    { 0 }
    { n - female male(n - 1) }
}

female = { n |
  true? n == 0
    { 1 }
    { n - male female(n - 1 ) }
}

p 0.to(20).map! { n | female n }
p 0.to(20).map! { n | male n }


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

/* let us declare our functions; indeed here we need
   really only M declaration, so that F can "see" it
   and the compiler won't complain with a warning */
int F(const int n);
int M(const int n);

int F(const int n)
{
  return (n == 0) ? 1 : n - M(F(n - 1));
}

int M(const int n)
{
  return (n == 0) ? 0 : n - F(M(n - 1));
}

int main(void)
{
  int i;
  for (i = 0; i < 20; i++)
    printf("%2d ", F(i));
  printf("\n");
  for (i = 0; i < 20; i++)
    printf("%2d ", M(i));
  printf("\n");
  return EXIT_SUCCESS;
}


namespace RosettaCode {
    class Hofstadter {
        static public int F(int n) {
            int result = 1;
            if (n > 0) {
                result = n - M(F(n-1));
            }

            return result;
        }

        static public int M(int n) {
            int result = 0;
            if (n > 0) {
                result = n - F(M(n - 1));
            }

            return result;
        }
    }
}


#include <iostream>
#include <vector>
#include <iterator>

class Hofstadter
{
public:
  static int F(int n) {
    if ( n == 0 ) return 1;
    return n - M(F(n-1));
  }
  static int M(int n) {
    if ( n == 0 ) return 0;
    return n - F(M(n-1));
  }
};

using namespace std;

int main()
{
  int i;
  vector<int> ra, rb;

  for(i=0; i < 20; i++) {
    ra.push_back(Hofstadter::F(i));
    rb.push_back(Hofstadter::M(i));
  }
  copy(ra.begin(), ra.end(),
       ostream_iterator<int>(cout, " "));
  cout << endl;
  copy(rb.begin(), rb.end(),
       ostream_iterator<int>(cout, " "));
  cout << endl;
  return 0;
}


Integer f(Integer n)
    =>  if (n > 0)
        then n - m(f(n-1))
        else 1;

Integer m(Integer n)
    =>  if (n > 0)
        then n - f(m(n-1))
        else 0;

shared void run() {
    printAll((0:20).map(f));
    printAll((0:20).map(m));
}


(declare F) ; forward reference

(defn M [n]
  (if (zero? n)
    0
    (- n (F (M (dec n))))))

(defn F [n]
  (if (zero? n)
    1
    (- n (M (F (dec n))))))


% At the top level, definitions can only see the definitions above.
% But if we put F and M in a cluster, they can see each other.
mutrec = cluster is F, M
    rep = null

    F = proc (n: int) returns (int)
        if n=0 then return(1)
        else return(n - M(F(n-1)))
        end
    end F

    M = proc (n: int) returns (int)
        if n=0 then return(0)
        else return(n - F(M(n-1)))
        end
    end M
end mutrec

% If we absolutely _must_ have them defined at the top level,
% we can then just take them out of the cluster.
F = mutrec$F
M = mutrec$M

% Print the first few values for F and M
print_first_16 = proc (name: string, fn: proctype (int) returns (int))
    po: stream := stream$primary_output()
    stream$puts(po, name || ":")
    for i: int in int$from_to(0,15) do
        stream$puts(po, " " || int$unparse(fn(i)))
    end
    stream$putl(po, "")
end print_first_16

start_up = proc ()
    print_first_16("F", F)
    print_first_16("M", M)
end start_up


F = (n) ->
  if n is 0 then 1 else n - M F n - 1

M = (n) ->
  if n is 0 then 0 else n - F M n - 1

console.log [0...20].map F
console.log [0...20].map M


import std.stdio, std.algorithm, std.range;

int male(in int n) pure nothrow {
    return n ? n - male(n - 1).female : 0;
}

int female(in int n) pure nothrow {
    return n ? n - female(n - 1).male : 1;
}

void main() {
    20.iota.map!female.writeln;
    20.iota.map!male.writeln;
}


unit Hofstadter;

interface

type
  THofstadterFemaleMaleSequences = class
  public
    class function F(n: Integer): Integer;
    class function M(n: Integer): Integer;
  end;

implementation

class function THofstadterFemaleMaleSequences.F(n: Integer): Integer;
begin
  Result:= 1;
  if (n > 0) then
    Result:= n - M(F(n-1));
end;

class function THofstadterFemaleMaleSequences.M(n: Integer): Integer;
begin
  Result:= 0;
  if (n > 0) then
    Result:= n - F(M(n - 1));
end;

end.


F n:
	if n:
		- n M F -- n
	else:
		1

M n:
	if n:
		- n F M -- n
	else:
		0

for i range 0 10:
	!.( M i F i )


/* We need to predeclare M if we want F to be able to see it.
 * This is done using 'extern', same as if it had been in a
 * different compilation unit. */
extern M(byte n) byte;

/* Mutually recursive functions */
proc F(byte n) byte:
    if n=0 then 1 else n - M(F(n-1)) fi
corp

proc M(byte n) byte:
    if n=0 then 0 else n - F(M(n-1)) fi
corp

/* Show the first 16 values of each */
proc nonrec main() void:
    byte i;

    write("F:");
    for i from 0 upto 15 do write(F(i):2) od;
    writeln();

    write("M:");
    for i from 0 upto 15 do write(M(i):2) od;
    writeln()
corp


class
	APPLICATION

create
	make

feature

	make
			-- Test of the mutually recursive functions Female and Male.
		do
			across
				0 |..| 19 as c
			loop
				io.put_string (Female (c.item).out + " ")
			end
			io.new_line
			across
				0 |..| 19 as c
			loop
				io.put_string (Male (c.item).out + " ")
			end
		end

	Female (n: INTEGER): INTEGER
			-- Female sequence of the Hofstadter Female and Male sequences.
		require
			n_not_negative: n >= 0
		do
			Result := 1
			if n /= 0 then
				Result := n - Male (Female (n - 1))
			end
		end

	Male (n: INTEGER): INTEGER
			-- Male sequence of the Hofstadter Female and Male sequences.
		require
			n_not_negative: n >= 0
		do
			Result := 0
			if n /= 0 then
				Result := n - Female (Male (n - 1))
			end
		end

end


import extensions;
import system'collections;

F = (n => (n == 0) ? 1 : (n - M(F(n-1))) );
M = (n => (n == 0) ? 0 : (n - F(M(n-1))) );

public program()
{
    var ra := new ArrayList();
    var rb := new ArrayList();

    for(int i := 0, i <= 19, i += 1)
    {
        ra.append(F(i));
        rb.append(M(i))
    };

    console.printLine(ra.asEnumerable());
    console.printLine(rb.asEnumerable())
}


defmodule MutualRecursion do
  def f(0), do: 1
  def f(n), do: n - m(f(n - 1))
  def m(0), do: 0
  def m(n), do: n - f(m(n - 1))
end

IO.inspect Enum.map(0..19, fn n -> MutualRecursion.f(n) end)
IO.inspect Enum.map(0..19, fn n -> MutualRecursion.m(n) end)


integer idM, idF

function F(integer n)
    if n = 0 then
        return 1
    else
        return n - call_func(idM,{F(n-1)})
    end if
end function

idF = routine_id("F")

function M(integer n)
    if n = 0 then
        return 0
    else
        return n - call_func(idF,{M(n-1)})
    end if
end function

idM = routine_id("M")


let rec f n =
    match n with
    | 0 -> 1
    | _ -> n - (m (f (n-1)))
and m n =
    match n with
    | 0 -> 0
    | _ -> n - (f (m (n-1)))


DEFER: F
: M ( n -- n' ) dup 0 = [ dup 1 - M F - ] unless ;
: F ( n -- n' ) dup 0 = [ drop 1 ] [ dup 1 - F M - ] if ;


class Main
{
  static Int f (Int n)
  {
    if (n <= 0) // ensure n > 0
      return 1
    else
      return n - m(f(n-1))
  }

  static Int m (Int n)
  {
    if (n <= 0) // ensure n > 0
      return 0
    else
      return n - f(m(n-1))
  }

  public static Void main ()
  {
    50.times |Int n| { echo (f(n)) }
  }
}


defer m

: f ( n -- n )
  dup 0= if 1+ exit then
  dup 1- recurse m - ;

:noname ( n -- n )
  dup 0= if exit then
  dup 1- recurse f - ;
is m

: test ( xt n -- ) cr 0 do i over execute . loop drop ;

' m [email protected] 20 test \ 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12
' f 20 test        \ 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12


module MutualRec
  implicit none
contains
  pure recursive function m(n) result(r)
    integer :: r
    integer, intent(in) :: n
    if ( n == 0 ) then
       r = 0
       return
    end if
    r = n - f(m(n-1))
  end function m

  pure recursive function f(n) result(r)
    integer :: r
    integer, intent(in) :: n
    if ( n == 0 ) then
       r = 1
       return
    end if
    r = n - m(f(n-1))
  end function f

end module


' FB 1.05.0 Win64

' Need forward declaration of M as it's used
' by F before its defined
Declare Function M(n As Integer) As Integer

Function F(n As Integer) As Integer
   If n = 0 Then
     Return 1
   End If
   Return n - M(F(n - 1))
End Function

Function M(n As Integer) As Integer
   If n = 0 Then
     Return 0
   End If
   Return n - F(M(n - 1))
End Function

Dim As Integer n = 24
Print "n :";
For i As Integer = 0 to n : Print Using "###"; i;    : Next
Print
Print String(78, "-")
Print "F :";
For i As Integer = 0 To n : Print Using "###"; F(i); : Next
Print
Print "M :";
For i As Integer = 0 To n : Print Using "###"; M(i); : Next
Print
Print "Press any key to quit"
Sleep


package main
import "fmt"

func F(n int) int {
  if n == 0 { return 1 }
  return n - M(F(n-1))
}

func M(n int) int {
  if n == 0 { return 0 }
  return n - F(M(n-1))
}

func main() {
  for i := 0; i < 20; i++ {
    fmt.Printf("%2d ", F(i))
  }
  fmt.Println()
  for i := 0; i < 20; i++ {
    fmt.Printf("%2d ", M(i))
  }
  fmt.Println()
}


def f, m  // recursive closures must be declared before they are defined
f = { n -> n == 0 ? 1 : n - m(f(n-1)) }
m = { n -> n == 0 ? 0 : n - f(m(n-1)) }


procedure main(arglist)
every write(F(!arglist))   # F of all arguments
end

procedure F(n)
if integer(n) >= 0 then
   return (n = 0, 1) |  n - M(F(n-1))
end

procedure M(n)
if integer(n) >= 0 then
   return (0 = n) | n - F(M(n-1))
end


mutual {
  F : Nat -> Nat
  F Z = (S Z)
  F (S n) = (S n) `minus` M(F(n))

  M : Nat -> Nat
  M Z = Z
  M (S n) = (S n) `minus` F(M(n))
}


f := method(n, if( n == 0, 1, n - m(f(n-1))))
m := method(n, if( n == 0, 0, n - f(m(n-1))))

Range
0 to(19) map(n,f(n)) println
0 to(19) map(n,m(n)) println


import java.util.HashMap;
import java.util.Map;

public class MutualRecursion {

    public static void main(final String args[]) {
        int max = 20;
        System.out.printf("First %d values of the Female sequence:  %n", max);
        for (int i = 0; i < max; i++) {
            System.out.printf("  f(%d) = %d%n", i, f(i));
        }
        System.out.printf("First %d values of the Male sequence:  %n", max);
        for (int i = 0; i < 20; i++) {
            System.out.printf("  m(%d) = %d%n", i, m(i));
        }
    }

    private static Map<Integer,Integer> F_MAP = new HashMap<>();

    private static int f(final int n) {
        if ( F_MAP.containsKey(n) ) {
            return F_MAP.get(n);
        }
        int fn = n == 0 ? 1 : n - m(f(n - 1));
        F_MAP.put(n, fn);
        return fn;
    }

    private static Map<Integer,Integer> M_MAP = new HashMap<>();

    private static int m(final int n) {
        if ( M_MAP.containsKey(n) ) {
            return M_MAP.get(n);
        }
        int mn = n == 0 ? 0 : n - f(m(n - 1));
        M_MAP.put(n, mn);
        return mn;
    }

}


function f(num) {
 return (num === 0) ? 1 : num - m(f(num - 1));
}

function m(num) {
 return (num === 0) ? 0 : num - f(m(num - 1));
}

function range(m, n) {
  return Array.apply(null, Array(n - m + 1)).map(
    function (x, i) { return m + i; }
  );
}

var a = range(0, 19);

//return a new array of the results and join with commas to print
console.log(a.map(function (n) { return f(n); }).join(', '));
console.log(a.map(function (n) { return m(n); }).join(', '));


def M:
  def F: if . == 0 then 1 else . - ((. - 1) | F | M) end;
  if . == 0 then 0 else . - ((. - 1) | M | F) end;

def F:
  if . == 0 then 1 else . - ((. - 1) | F | M) end;


/* Mutual recursion, is jsish */
function f(num):number { return (num === 0) ? 1 : num - m(f(num - 1)); }
function m(num):number { return (num === 0) ? 0 : num - f(m(num - 1)); }

function range(n=10, start=0, step=1):array {
   var a = Array(n).fill(0);
   for (var i in a) a[i] = start+i*step;
   return a;
}

var a = range(21);
puts(a.map(function (n) { return f(n); }).join(', '));
puts(a.map(function (n) { return m(n); }).join(', '));

/*
=!EXPECTSTART!=
1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 11, 11, 12, 13
0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 7, 8, 9, 9, 10, 11, 11, 12, 12
=!EXPECTEND!=
*/


// version 1.0.6

fun f(n: Int): Int =
    when {
        n == 0 -> 1
        else   -> n - m(f(n - 1))
    }

fun m(n: Int): Int =
    when {
        n == 0 -> 0
        else   -> n - f(m(n - 1))
    }

fun main(args: Array<String>) {
    val n = 24
    print("n :")
    for (i in 0..n) print("%3d".format(i))
    println()
    println("-".repeat(78))
    print("F :")
    for (i in 0..24) print("%3d".format(f(i)))
    println()
    print("M :")
    for (i in 0..24) print("%3d".format(m(i)))
    println()
}


print "F sequence."
for i = 0 to 20
print f(i);" ";
next
print
print "M sequence."
for i = 0 to 20
print m(i);" ";
next

end

function f(n)
    if n = 0 then
        f = 1
    else
        f = n - m(f(n - 1))
    end if
    end function

function m(n)
    if n = 0 then
        m = 0
    else
        m = n - f(m(n - 1))
    end if
    end function


'// LibreOffice Basic Implementation of Hofstadter Female-Male sequences

'// Utility functions
sub setfont(strfont)
	ThisComponent.getCurrentController.getViewCursor.charFontName = strfont
end sub

sub newline
	oVC = thisComponent.getCurrentController.getViewCursor
	oText = oVC.text
	oText.insertControlCharacter(oVC, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False)
end sub

sub out(sString)
	oVC = ThisComponent.getCurrentController.getViewCursor
	oText = oVC.text
	oText.insertString(oVC, sString, false)
end sub

sub outln(optional sString)
	if not ismissing (sString) then out(sString)
	newline
end sub

function intformat(n as integer,nlen as integer) as string
	dim nstr as string
	nstr = CStr(n)
	while len(nstr) < nlen
		nstr = " " & nstr
	wend
	intformat = nstr
end function

'// Hofstadter Female-Male function definitions
function F(n as long) as long
	if n = 0 Then
		F =  1
	elseif n > 0 Then
		F = n - M(F(n - 1))
	endif
end function

function M(n)
	if n = 0 Then
		M = 0
	elseif n > 0 Then
		M = n - F(M(n - 1))
	endif
end function

'// Hofstadter Female Male sequence demo routine
sub Hofstadter_Female_Male_Demo
	'// Introductory Text
	setfont("LM Roman 10")
	outln("Rosetta Code Hofstadter Female and Male Sequence Challenge")
	outln
	out("Two functions are said to be mutually recursive if the first calls the second,")
	outln(" and in turn the second calls the first.")
	out("Write two mutually recursive functions that compute members of the Hofstadter")
	outln(" Female and Male sequences defined as:")
	outln
	setfont("LM Mono Slanted 10")
	outln(chr(9)+"F(0) = 1 ; M(0)=0")
	outln(chr(9)+"F(n) = n - M(F(n-1)), n > 0")
	outln(chr(9)+"M(n) = n - F(M(n-1)), n > 0")
	outln
	'// Sequence Generation
	const nmax as long = 20
	dim n as long
	setfont("LM Mono 10")
	out("n    = "
	for n = 0 to nmax
		out(" " + intformat(n, 2))
	next n
	outln
	out("F(n) = "
	for n = 0 to nmax
		out(" " + intformat(F(n),2))
	next n
	outln
	out("M(n) = "
	for n = 0 to nmax
		out(" " + intformat(M(n), 2))
	next n
	outln

end sub

------------------------------
Output
------------------------------
n    =   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
F(n) =   1  1  2  2  3  3  4  5  5  6  6  7  8  8  9  9 10 11 11 12 13
M(n) =   0  0  1  2  2  3  4  4  5  6  6  7  7  8  9  9 10 11 11 12 12


integer iDEPTH = 100;
integer f(integer n) {
	if(n==0) {
		return 1;
	} else {
		return n-m(f(n - 1));
	}
}
integer m(integer n) {
	if(n==0) {
		return 0;
	} else {
		return n-f(m(n - 1));
	}
}
default {
	state_entry() {
		integer x = 0;
		string s = "";
		for(x=0 ; x<iDEPTH ; x++) {
			s += (string)(f(x))+" ";
		}
		llOwnerSay(llList2CSV(llParseString2List(s, [" "], [])));
		s = "";
		for(x=0 ; x<iDEPTH ; x++) {
			s += (string)(m(x))+" ";
		}
		llOwnerSay(llList2CSV(llParseString2List(s, [" "], [])));
	}
}


function m(n) return n > 0 and n - f(m(n-1)) or 0 end
function f(n) return n > 0 and n - m(f(n-1)) or 1 end


\\ set console 70 characters by 40 lines
Form 70, 40
Module CheckSubs {
      Flush
      Document one$, two$
      For i =0 to 20
            Print format$("{0::-3}",i);
            f(i)
            \\  number pop then top value of stack
            one$=format$("{0::-3}",number)
            m(i)
            two$=format$("{0::-3}",number)
      Next i
      Print
      Print one$
      Print two$
      Sub f(x)
            if x<=0 then Push 1 : Exit sub
            f(x-1)  ' leave result to for m(x)
            m()
            push x-number
      End Sub
      Sub m(x)
            if x<=0 then Push 0 : Exit sub
            m(x-1)
            f()
            push x-number
      End Sub
}
CheckSubs

Module Checkit {
      Function global f(n) {
            if n=0 then =1: exit
            if n>0 then  =n-m(f(n-1))
      }
      Function global m(n) {
            if n=0 then =0
            if n>0 then  =n-f(m(n-1))

      }
      Document one$, two$
      For i =0 to 20
            Print format$("{0::-3}",i);
            one$=format$("{0::-3}",f(i))
            two$=format$("{0::-3}",m(i))
      Next i
      Print
      Print one$
      Print two$
}
Checkit
Module Checkit2 {
      Group Alfa {
            function f(n) {
                  if n=0 then =1: exit
                  if n>0 then  =n-.m(.f(n-1))
            }
            function m(n) {
                  if n=0 then =0
                  if n>0 then  =n-.f(.m(n-1))
            }
      }
      Document one$, two$
      For i =0 to 20
            Print format$("{0::-3}",i);
            one$=format$("{0::-3}",Alfa.f(i))
            two$=format$("{0::-3}",Alfa.m(i))
      Next i
      Print
      Print one$
      Print two$
      Clipboard one$+{
      }+two$
}
Checkit2


define(`female',`ifelse(0,$1,1,`eval($1 - male(female(decr($1))))')')dnl
define(`male',`ifelse(0,$1,0,`eval($1 - female(male(decr($1))))')')dnl
define(`loop',`ifelse($1,$2,,`$3($1) loop(incr($1),$2,`$3')')')dnl
loop(0,20,`female')
loop(0,20,`male')


            NORMAL MODE IS INTEGER

          R SET UP STACK SPACE

            DIMENSION STACK(100)
            SET LIST TO STACK

          R DEFINE RECURSIVE FUNCTIONS
          R INPUT ARGUMENT ASSUMED TO BE IN N

            INTERNAL FUNCTION(DUMMY)
            ENTRY TO FREC.
            WHENEVER N.LE.0, FUNCTION RETURN 1
            SAVE RETURN
            SAVE DATA N
            N = N-1
            N = FREC.(0)
            X = MREC.(0)
            RESTORE DATA N
            RESTORE RETURN
            FUNCTION RETURN N-X
            END OF FUNCTION

            INTERNAL FUNCTION(DUMMY)
            ENTRY TO MREC.
            WHENEVER N.LE.0, FUNCTION RETURN 0
            SAVE RETURN
            SAVE DATA N
            N = N-1
            N = MREC.(0)
            X = FREC.(0)
            RESTORE DATA N
            RESTORE RETURN
            FUNCTION RETURN N-X
            END OF FUNCTION

          R DEFINE FRONT-END FUNCTIONS THAT CAN BE CALLED WITH ARGMT

            INTERNAL FUNCTION(NN)
            ENTRY TO F.
            N = NN
            FUNCTION RETURN FREC.(0)
            END OF FUNCTION

            INTERNAL FUNCTION(NN)
            ENTRY TO M.
            N = NN
            FUNCTION RETURN MREC.(0)
            END OF FUNCTION

          R PRINT F(0..19) AND M(0..19)

            THROUGH SHOW, FOR I=0, 1, I.GE.20
SHOW        PRINT FORMAT FMT,I,F.(I),I,M.(I)
            VECTOR VALUES FMT =
          0      $2HF(,I2,4H) = ,I2,S8,2HM(,I2,4H) = ,I2*$
            END OF PROGRAM


female_seq := proc(n)
	if (n = 0) then
		return 1;
	else
		return n - male_seq(female_seq(n-1));
	end if;
end proc;

male_seq  := proc(n)
	if (n = 0) then
		return 0;
	else
		return n - female_seq(male_seq(n-1));
	end if;
end proc;
seq(female_seq(i), i=0..10);
seq(male_seq(i), i=0..10);


function Fn = female(n)

    if n == 0
        Fn = 1;
        return
    end

    Fn = n - male(female(n-1));
end


:- module mutual_recursion.
:- interface.

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

:- implementation.
:- import_module int, list.

main(!IO) :-
   io.write(list.map(f, 0..19), !IO), io.nl(!IO),
   io.write(list.map(m, 0..19), !IO), io.nl(!IO).

:- func f(int) = int.

f(N) = ( if N = 0 then 1 else N - m(f(N - 1)) ).

:- func m(int) = int.

m(N) = ( if N = 0 then 0 else N - f(m(N - 1)) ).


f = function(n)
    if n > 0 then return n - m(f(n - 1))
    return 1
end function

m = function(n)
    if n > 0 then return n - f(m(n - 1))
    return 0
end function

print f(12)
print m(12)


	LOC	Data_Segment

	GREG	@
NL	BYTE	#a,0
	GREG	@
buf	OCTA	0,0

t	IS	$128
Ja	IS	$127

	LOC #1000

	GREG @
// print 2 digits integer with trailing space to StdOut
// reg $3 contains int to be printed
bp	IS	$71
0H	GREG	#0000000000203020
prtInt	STO	0B,buf		% initialize buffer
	LDA	bp,buf+7	% points after LSD
				% REPEAT
1H	SUB	bp,bp,1		%  move buffer pointer
	DIV	$3,$3,10		%  divmod (x,10)
	GET	t,rR		%  get remainder
	INCL	t,'0'		%  make char digit
	STB	t,bp		%  store digit
	PBNZ	$3,1B		% UNTIL no more digits
	LDA	$255,bp
	TRAP	0,Fputs,StdOut	% print integer
	GO	Ja,Ja,0		% 'return'

// Female function
F	GET	$1,rJ		% save return addr
	PBNZ	$0,1F		% if N != 0 then F N
	INCL	$0,1		% F 0 = 1
	PUT	rJ,$1		% restore return addr
	POP	1,0		% return 1
1H	SUBU	$3,$0,1		% N1 = N - 1
	PUSHJ	$2,F		% do F (N - 1)
	ADDU	$3,$2,0		% place result in arg. reg.
	PUSHJ	$2,M		% do M F ( N - 1)
	PUT	rJ,$1		% restore ret addr
	SUBU	$0,$0,$2
	POP	1,0		% return N - M F ( N - 1 )

// Male function
M	GET	$1,rJ
	PBNZ	$0,1F
	PUT	rJ,$1
	POP	1,0		% return M 0 = 0
1H	SUBU	$3,$0,1
	PUSHJ	$2,M
	ADDU	$3,$2,0
	PUSHJ	$2,F
	PUT	rJ,$1
	SUBU	$0,$0,$2
	POP	1,0		$ return N - F M ( N - 1 )

// do a female run
Main	SET	$1,0		% for (i=0; i<25; i++){
1H	ADDU	$4,$1,0		%
	PUSHJ	$3,F		%  F (i)
	GO	Ja,prtInt	%  print F (i)
	INCL	$1,1
	CMP	t,$1,25
	PBNZ	t,1B		% }
	LDA	$255,NL
	TRAP	0,Fputs,StdOut
// do a male run
	SET	$1,0		% for (i=0; i<25; i++){
1H	ADDU	$4,$1,0		%
	PUSHJ	$3,M		%  M (i)
	GO	Ja,prtInt	%  print M (i)
	INCL	$1,1
	CMP	t,$1,25
	PBNZ	t,1B		% }
	LDA	$255,NL
	TRAP	0,Fputs,StdOut
	TRAP	0,Halt,0


MODULE MutualRecursion;
FROM InOut IMPORT WriteCard, WriteString, WriteLn;

TYPE Fn = PROCEDURE(CARDINAL): CARDINAL;

PROCEDURE F(n: CARDINAL): CARDINAL;
BEGIN
    IF n=0 THEN RETURN 1;
    ELSE RETURN n-M(F(n-1));
    END;
END F;

PROCEDURE M(n: CARDINAL): CARDINAL;
BEGIN
    IF n=0 THEN RETURN 0;
    ELSE RETURN n-F(M(n-1));
    END;
END M;

(* Print the first few values of one of the functions *)
PROCEDURE Show(name: ARRAY OF CHAR; fn: Fn);
    CONST Max = 15;
    VAR i: CARDINAL;
BEGIN
    WriteString(name);
    WriteString(": ");
    FOR i := 0 TO Max DO
        WriteCard(fn(i), 0);
        WriteString(" ");
    END;
    WriteLn;
END Show;

(* Show the first values of both F and M *)
BEGIN
    Show("F", F);
    Show("M", M);
END MutualRecursion.


using System;
using System.Console;

module Hofstadter
{
    F(n : int) : int
    {
        |0 => 1
        |_ => n - M(F(n - 1))
    }

    M(n : int) : int
    {
        |0 => 0
        |_ => n - F(M(n - 1))
    }

    Main() : void
    {
        foreach (n in [0 .. 20]) Write("{0} ", F(n));
        WriteLine();
        foreach (n in [0 .. 20]) Write("{0} ", M(n));
    }
}


proc m(n: int): int

proc f(n: int): int =
  if n == 0: 1
  else: n - m(f(n-1))

proc m(n: int): int =
  if n == 0: 0
  else: n - f(m(n-1))

for i in 1 .. 10:
  echo f(i)
  echo m(i)


class MutualRecursion {
  function : Main(args : String[]) ~ Nil {
    for(i := 0; i < 20; i+=1;) {
      f(i)->PrintLine();
    };
    "---"->PrintLine();
    for (i := 0; i < 20; i+=1;) {
      m(i)->PrintLine();
    };
  }

  function : f(n : Int) ~ Int {
    return n = 0 ? 1 : n - m(f(n - 1));
  }

  function : m(n : Int) ~ Int {
    return n = 0 ? 0 : n - f(m(n - 1));
  }
}


#import <Foundation/Foundation.h>

@interface Hofstadter : NSObject
+ (int)M: (int)n;
+ (int)F: (int)n;
@end

@implementation Hofstadter
+ (int)M: (int)n
{
  if ( n == 0 ) return 0;
  return n - [self F: [self M: (n-1)]];
}
+ (int)F: (int)n
{
  if ( n == 0 ) return 1;
  return n - [self M: [self F: (n-1)]];
}
@end

int main()
{
  int i;

  for(i=0; i < 20; i++) {
    printf("%3d ", [Hofstadter F: i]);
  }
  printf("\n");
  for(i=0; i < 20; i++) {
    printf("%3d ", [Hofstadter M: i]);
  }
  printf("\n");
  return 0;
}


let rec f = function
  | 0 -> 1
  | n -> n - m(f(n-1))
and m = function
  | 0 -> 0
  | n -> n - f(m(n-1))
;;


function r = F(n)
  for i = 1:length(n)
    if (n(i) == 0)
      r(i) = 1;
    else
      r(i) = n(i) - M(F(n(i)-1));
    endif
  endfor
endfunction

function r = M(n)
  for i = 1:length(n)
    if (n(i) == 0)
      r(i) = 0;
    else
      r(i) = n(i) - F(M(n(i)-1));
    endif
  endfor
endfunction


Method new: M

Integer method: F
   self 0 == ifTrue: [ 1 return ]
   self self 1 - F M - ;

Integer method: M
   self 0 == ifTrue: [ 0 return ]
   self self 1 - M F - ;

0 20 seqFrom map(#F) println
0 20 seqFrom map(#M) println


#include <order/interpreter.h>

#define ORDER_PP_DEF_8f                         \
ORDER_PP_FN(8fn(8N,                             \
                8if(8is_0(8N),                  \
                    1,                          \
                    8sub(8N, 8m(8f(8dec(8N)))))))

#define ORDER_PP_DEF_8m                         \
ORDER_PP_FN(8fn(8N,                             \
                8if(8is_0(8N),                  \
                    0,                          \
                    8sub(8N, 8f(8m(8dec(8N)))))))

//Test
ORDER_PP(8for_each_in_range(8fn(8N, 8print(8f(8N))), 0, 19))
ORDER_PP(8for_each_in_range(8fn(8N, 8print(8m(8N))), 0, 19))


declare
  fun {F N}
     if N == 0 then 1
     elseif N > 0 then N - {M {F N-1}}
     end
  end

  fun {M N}
     if N == 0 then 0
     elseif N > 0 then N - {F {M N-1}}
     end
  end
in
  {Show {Map {List.number 0 9 1} F}}
  {Show {Map {List.number 0 9 1} M}}


Program MutualRecursion;

{M definition comes after F which uses it}
function M(n : Integer) : Integer; forward;

function F(n : Integer) : Integer;
begin
   if n = 0 then
      F := 1
   else
      F := n - M(F(n-1));
end;

function M(n : Integer) : Integer;
begin
   if n = 0 then
      M := 0
   else
      M := n - F(M(n-1));
end;

var
   i : Integer;

begin
   for i := 0 to 19 do begin
      write(F(i) : 4)
   end;
   writeln;
   for i := 0 to 19 do begin
      write(M(i) : 4)
   end;
   writeln;
end.


sub F { my $n = shift; $n ? $n - M(F($n-1)) : 1 }
sub M { my $n = shift; $n ? $n - F(M($n-1)) : 0 }

# Usage:
foreach my $sequence (\&F, \&M) {
    print join(' ', map $sequence->($_), 0 .. 19), "\n";
}


with javascript_semantics
forward function M(integer n)

function F(integer n)
    return iff(n?n-M(F(n-1)):1)
end function

function M(integer n)
    return iff(n?n-F(M(n-1)):0)
end function

for i=0 to 20 do
    printf(1," %d",F(i))
end for
printf(1,"\n")
for i=0 to 20 do
    printf(1," %d",M(i))
end for


<?php
function F($n)
{
  if ( $n == 0 ) return 1;
  return $n - M(F($n-1));
}

function M($n)
{
  if ( $n == 0) return 0;
  return $n - F(M($n-1));
}

$ra = array();
$rb = array();
for($i=0; $i < 20; $i++)
{
  array_push($ra, F($i));
  array_push($rb, M($i));
}
echo implode(" ", $ra) . "\n";
echo implode(" ", $rb) . "\n";
?>


test: procedure options (main);

M: procedure (n) returns (fixed) recursive;    /* 8/1/2010 */
   declare n fixed;
   if n <= 0 then return (0);
   else return ( n - F(M(n-1)) );
end M;

F: procedure (n) returns (fixed) recursive;
   declare n fixed;
   if n <= 0 then return (1);
   else return ( n - M(F(n-1)) );
end F;

   declare i fixed;

   do i = 1 to 15;
      put skip list ( F(i), M(i) );
   end;
end test;


/female{
/n exch def
n 0 eq
{1}
{
n n 1 sub female male sub
}ifelse
}def

/male{
/n exch def
n 0 eq
{0}
{
n n 1 sub male female sub
}ifelse
}def


function F($n) {
    if ($n -eq 0) { return 1 }
    return $n - (M (F ($n - 1)))
}

function M($n) {
    if ($n -eq 0) { return 0 }
    return $n - (F (M ($n - 1)))
}


female(0,1).
female(N,F) :- N>0,
	       N1 is N-1,
	       female(N1,R),
	       male(R, R1),
	       F is N-R1.

male(0,0).
male(N,F) :- N>0,
	     N1 is N-1,
	     male(N1,R),
	     female(R, R1),
	     F is N-R1.


Declare M(n)

Procedure F(n)
  If n = 0
    ProcedureReturn 1
  ElseIf n > 0
    ProcedureReturn n - M(F(n - 1))
  EndIf
EndProcedure

Procedure M(n)
  If n = 0
    ProcedureReturn 0
  ElseIf n > 0
    ProcedureReturn n - F(M(n - 1))
  EndIf
EndProcedure

Define i
If OpenConsole()

  For i = 0 To 19
    Print(Str(F(i)))
    If i = 19
      Continue
    EndIf
    Print(", ")
  Next

  PrintN("")
  For i = 0 To 19
    Print(Str(M(i)))
    If i = 19
      Continue
    EndIf
    Print(", ")
  Next

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf


def F(n): return 1 if n == 0 else n - M(F(n-1))
def M(n): return 0 if n == 0 else n - F(M(n-1))

print ([ F(n) for n in range(20) ])
print ([ M(n) for n in range(20) ])


                  forward is f ( n --> n )

  [ dup 0 = if done
    dup 1 - recurse f - ] is m ( n --> n )

  [ dup 0 = iff 1+ done
    dup 1 - recurse m - ]
                    resolves f ( n --> n )

  say "f = "
  20 times [ i^ f echo sp ] cr
  say "m = "
  20 times [ i^ m echo sp ] cr


F <- function(n) ifelse(n == 0, 1, n - M(F(n-1)))
M <- function(n) ifelse(n == 0, 0, n - F(M(n-1)))


#lang racket
(define (F n)
  (if (>= 0 n)
      1
      (- n (M (F (sub1 n))))))

(define (M n)
  (if (>= 0 n)
      0
      (- n (F (M (sub1 n))))))


rebol [
    Title: "Mutual Recursion"
    URL: http://rosettacode.org/wiki/Mutual_Recursion
	References: [http://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Female_and_Male_sequences]
]

f: func [
	"Female."
	n [integer!] "Value."
] [either 0 = n [1][n - m f n - 1]]

m: func [
	"Male."
	n [integer!] "Value."
] [either 0 = n [0][n - f m n - 1]]

fs: []  ms: []  for i 0 19 1 [append fs f i  append ms m i]
print ["F:" mold fs  crlf  "M:" mold ms]


/*REXX program shows  mutual recursion  (via the Hofstadter Male and Female sequences). */
parse arg lim .;      if lim=''  then lim= 40;     w= length(lim);      pad= left('', 20)

     do j=0  for lim+1;   jj= right(j, w);   ff= right(F(j), w);        mm= right(M(j), w)
     say    pad       'F('jj") ="            ff   pad   'M('jj") ="     mm
     end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
F: procedure;  parse arg n;   if n==0  then return 1;           return  n - M( F(n-1) )
M: procedure;  parse arg n;   if n==0  then return 0;           return  n - F( M(n-1) )


see "F sequence : "
for i = 0 to 20
    see "" + f(i) + " "
next
see nl
see "M sequence : "
for i = 0 to 20
    see "" + m(i) + " "
next

func f n
     fr = 1
     if n != 0 fr = n - m(f(n - 1)) ok
     return fr

func m n
     mr = 0
     if n != 0 mr = n - f(m(n - 1)) ok
     return mr


print "F sequence:";
for i = 0 to 20
  print f(i);" ";
next i
print :print "M sequence:";
for i = 0 to 20
  print m(i);" ";
next i
end

function f(n)
 f = 1
 if n <> 0 then f = n - m(f(n - 1))
end function

function m(n)
 m = 0
 if n <> 0 then m = n - f(m(n - 1))
end function


% Forward definitions: [also deletes any existing definition]
define f();
define m();

define f(n) {
  if (n == 0) return 1;
  else if (n < 0) error("oops");
  return n - m(f(n - 1));
}

define m(n) {
  if (n == 0) return 0;
  else if (n < 0) error("oops");
  return n - f(m(n - 1));
}

foreach $1 ([0:19])
  () = printf("%d  ", f($1));
() = printf("\n");
foreach $1 ([0:19])
  () = printf("%d  ", m($1));
() = printf("\n");


class MAIN is

  f(n:INT):INT
    pre n >= 0
  is
    if n = 0 then return 1; end;
    return n - m(f(n-1));
  end;

  m(n:INT):INT
    pre n >= 0
  is
    if n = 0 then return 0; end;
    return n - f(m(n-1));
  end;

  main is
    loop i ::= 0.upto!(19);
      #OUT + #FMT("%2d ", f(i));
    end;
    #OUT + "\n";
    loop i ::= 0.upto!(19);
      #OUT + #FMT("%2d ", m(i));
    end;
  end;
end;


def F(n:Int):Int =
  if (n == 0) 1 else n - M(F(n-1))
def M(n:Int):Int =
  if (n == 0) 0 else n - F(M(n-1))

println((0 until 20).map(F).mkString(", "))
println((0 until 20).map(M).mkString(", "))


$ include "seed7_05.s7i";

const func integer: m (in integer: n) is forward;

const func integer: f (in integer: n) is func
  result
    var integer: res is 0;
  begin
    if n = 0 then
      res := 1;
    else
      res := n - m(f(n - 1));
    end if;
  end func;

const func integer: m (in integer: n) is func
  result
    var integer: res is 0;
  begin
    if n = 0 then
      res := 0;
    else
      res := n - f(m(n - 1));
    end if;
  end func;

const proc: main is func
  local
    var integer: i is 0;
  begin
    for i range 0 to 19 do
      write(f(i) lpad 3);
    end for;
    writeln;
    for i range 0 to 19 do
      write(m(i) lpad 3);
    end for;
    writeln;
  end func;


|F M ra rb|

F := [ :n |
  (n == 0)
    ifTrue: [ 1 ]
    ifFalse: [ n - (M value: (F value: (n-1))) ]
].

M := [ :n |
  (n == 0)
    ifTrue: [ 0 ]
    ifFalse: [ n - (F value: (M value: (n-1))) ]
].

ra := OrderedCollection new.
rb := OrderedCollection new.
0 to: 19 do: [ :i |
  ra add: (F value: i).
  rb add: (M value: i)
].

ra displayNl.
rb displayNl.


        define('f(n)') :(f_end)
f       f = eq(n,0) 1 :s(return)
        f = n - m(f(n - 1)) :(return)
f_end

        define('m(n)') :(m_end)
m       m = eq(n,0) 0 :s(return)
        m = n - f(m(n - 1)) :(return)
m_end

*       # Test and display
L1      s1 = s1 m(i) ' ' ; s2 = s2 f(i) ' '
        i = le(i,25) i + 1 :s(L1)
        output = 'M: ' s1; output = 'F: ' s2
end


func F(n: Int) -> Int {
  return n == 0 ? 1 : n - M(F(n-1))
}

func M(n: Int) -> Int {
  return n == 0 ? 0 : n - F(M(n-1))
}

for i in 0..20 {
  print("\(F(i)) ")
}
println()
for i in 0..20 {
  print("\(M(i)) ")
}
println()


F param Fn
  if Fn = 0
     1 R
  else
     (Fn-1) nm1
     save Fn
     call F nm1
     result Fr
     save Fr
     call M Fr
     result Mr
     restore Fr
     restore Fn
     (Fn-Mr) R
  endif
  return R

M param Mn
  if Mn = 0
     0 R
  else
     (Mn-1) nm1
     save Mn
     call M nm1
     result Mr
     save Mr
     call F Mr
     result Fr
     restore Mr
     restore Mn
     (Mn-Fr) R
  endif
  return R

start

 i
 if i <= 19
    call F i
    result res
    " $s res ' '" $s
    + i
    goif
 endif
 $s []
 $s

 i
 if i <= 19
    call M i
    result res
    " $s res ' '" $s
    + i
    goif
 endif
 $s []


templates male
  when <=0> do 0 !
  otherwise def n: $;
     $n - 1 -> male -> female -> $n - $ !
end male

templates female
  when <=0> do 1 !
  otherwise def n: $;
     $n - 1 -> female -> male -> $n - $ !
end female

0..10 -> 'M$;: $->male; F$;: $->female;
' -> !OUT::write


proc m {n} {
    if { $n == 0 } { expr 0; } else {
	expr {$n - [f [m [expr {$n-1}] ]]};
    }
}
proc f {n} {
    if { $n == 0 } { expr 1; } else {
	expr {$n - [m [f [expr {$n-1}] ]]};
    }
}

for {set i 0} {$i < 20} {incr i} {
    puts -nonewline [f $i];
    puts -nonewline " ";
}
puts ""
for {set i 0} {$i < 20} {incr i} {
    puts -nonewline [m $i];
    puts -nonewline " ";
}
puts ""


Define F(n) = when(n=0, 1, n - M(F(n - 1)))
Define M(n) = when(n=0, 0, n - F(M(n - 1)))


LOCAL(1)                               ' main uses locals as well

FOR [email protected] = 0 TO 200                      ' set the array
  @([email protected]) = -1
NEXT

PRINT "F sequence:"                    ' print the F-sequence
FOR [email protected] = 0 TO 20
  PRINT FUNC(_f([email protected]));" ";
NEXT
PRINT

PRINT "M sequence:"                    ' print the M-sequence
FOR [email protected] = 0 TO 20
  PRINT FUNC(_m([email protected]));" ";
NEXT
PRINT

END

_f PARAM(1)                            ' F-function
  IF [email protected] = 0 THEN RETURN (1)            ' memoize the solution
  IF @([email protected]) < 0 THEN @([email protected]) = [email protected] - FUNC(_m(FUNC(_f([email protected] - 1))))
RETURN (@([email protected]))                         ' return array element

_m PARAM(1)                            ' M-function
  IF [email protected] = 0 THEN RETURN (0)            ' memoize the solution
  IF @([email protected]+100) < 0 THEN @([email protected]+100) = [email protected] - FUNC(_f(FUNC(_m([email protected] - 1))))
RETURN (@([email protected]+100))                     ' return array element


M()
{
    local n
    n=$1
    if [[ $n -eq 0 ]]; then
	echo -n 0
    else
	echo -n $(( n - $(F $(M $((n-1)) ) ) ))
    fi
}

F()
{
    local n
    n=$1
    if [[ $n -eq 0 ]]; then
	echo -n 1
    else
	echo -n $(( n - $(M $(F $((n-1)) ) ) ))
    fi
}

for((i=0; i < 20; i++)); do
    F $i
    echo -n " "
done
echo
for((i=0; i < 20; i++)); do
    M $i
    echo -n " "
done
echo


#import std
#import nat
#import sol

#fix general_function_fixer 0

F = ~&?\1! difference^/~& M+ F+ predecessor
M = ~&?\0! difference^/~& F+ M+ predecessor


Private Function F(ByVal n As Integer) As Integer
    If n = 0 Then
        F = 1
    Else
        F = n - M(F(n - 1))
    End If
End Function

Private Function M(ByVal n As Integer) As Integer
    If n = 0 Then
        M = 0
    Else
        M = n - F(M(n - 1))
    End If
End Function

Public Sub MR()
    Dim i As Integer
    For i = 0 To 20
        Debug.Print F(i);
    Next i
    Debug.Print
    For i = 0 To 20
        Debug.Print M(i);
    Next i
End Sub


var M  // forward declaration

var F = Fn.new { |n|
    if (n == 0) return 1
    return n - M.call(F.call(n-1))
}

M = Fn.new { |n|
    if (n == 0) return 0
    return n - F.call(M.call(n-1))
}

System.write("F(0..20): ")
(0..20).each { |i| System.write("%(F.call(i))  ") }
System.write("\nM(0..20): ")
(0..20).each { |i| System.write("%(M.call(i))  ") }
System.print()


	global	main
	extern	printf

	section	.text

func_f
	mov	eax, [esp+4]
	cmp	eax, 0
	jz	f_ret
	dec	eax
	push	eax
	call	func_f
	mov	[esp+0], eax
	call	func_m
	add	esp, 4
	mov	ebx, [esp+4]
	sub	ebx, eax
	mov	eax, ebx
	ret
f_ret
	mov	eax, 1
	ret

func_m
	mov	eax, [esp+4]
	cmp	eax, 0
	jz	m_ret
	dec	eax
	push	eax
	call	func_m
	mov	[esp+0], eax
	call	func_f
	add	esp, 4
	mov	ebx, [esp+4]
	sub	ebx, eax
	mov	eax, ebx
	ret
m_ret
	xor	eax, eax
	ret

main
	mov	edx, func_f
	call	output_res
	mov	edx, func_m
	call	output_res
	ret

output_res
	xor	ecx, ecx
loop0
	push	ecx
	call	edx

        push    edx

	push	eax
	push	form
	call	printf
	add	esp, 8

	pop     edx
        pop     ecx

	inc	ecx
	cmp	ecx, 20
	jnz	loop0

	push	newline
	call	printf
	add	esp, 4

	ret

	section	.rodata
form
	db	'%d ',0
newline
	db	10,0

	end


code    ChOut=8, CrLf=9, IntOut=11;

ffunc M; \forward-referenced function declaration

func F(N);
int N;
return if N=0 then 1 else N - M(F(N-1));

func M(N);
int N;
return if N=0 then 0 else N - F(M(N-1));

int I;
[for I:= 0 to 19 do [IntOut(0, F(I));  ChOut(0, ^ )];
CrLf(0);
 for I:= 0 to 19 do [IntOut(0, M(I));  ChOut(0, ^ )];
CrLf(0);
]


// User defined functions
sub F(n)
    if n = 0 return 1
    return n - M(F(n-1))
end sub

sub M(n)
   if n = 0 return 0
   return n - F(M(n-1))
end sub

for i = 0 to 20
    print F(i) using "###";
next
print
for i = 0 to 20
    print M(i) using "###";
next
print


T.enum Kind
   STRING
   NUMBER

T KeyItem
   Kind kind
   String s
   Int num

F natOrderKey(=s)
   // Remove leading and trailing white spaces.
   s = s.trim((‘ ’, "\t", "\r", "\n"))

   // Make all whitespace characters equivalent and remove adjacent spaces.
   s = s.replace(re:‘\s+’, ‘ ’)

   // Switch to lower case.
   s = s.lowercase()

   // Remove leading "the ".
   I s.starts_with(‘the ’) & s.len > 4
      s = s[4..]

   // Split into fields.
   [KeyItem] result
   V idx = 0
   L idx < s.len
      V e = idx
      L e < s.len & !s[e].is_digit()
         e++
      I e > idx
         V ki = KeyItem()
         ki.kind = Kind.STRING
         ki.s = s[idx .< e]
         result.append(ki)
         idx = e
      L e < s.len & s[e].is_digit()
         e++
      I e > idx
         V ki = KeyItem()
         ki.kind = Kind.NUMBER
         ki.num = Int(s[idx .< e])
         result.append(ki)
         idx = e
   R result

F scmp(s1, s2)
   I s1 < s2 {R -1}
   I s1 > s2 {R  1}
   R 0

F naturalCmp(String sa, String sb)
   V a = natOrderKey(sa)
   V b = natOrderKey(sb)

   L(i) 0 .< min(a.len, b.len)
      V ai = a[i]
      V bi = b[i]
      I ai.kind == bi.kind
         V result = I ai.kind == STRING {scmp(ai.s, bi.s)} E ai.num - bi.num
         I result != 0
            R result
      E
         R I ai.kind == STRING {1} E -1

   R I a.len < b.len {-1} E (I a.len == b.len {0} E 1)

F test(title, list)
   print(title)
   print(sorted(list, key' cmp_to_key(naturalCmp)).map(s -> ‘'’s‘'’).join("\n"))
   print()

test(‘Ignoring leading spaces.’,
    [‘ignore leading spaces:  2-2’,
     ‘ ignore leading spaces:  2-1’,
     ‘  ignore leading spaces:  2+0’,
     ‘   ignore leading spaces:  2+1’])

test(‘Ignoring multiple adjacent spaces (MAS).’,
    [‘ignore MAS spaces:  2-2’,
     ‘ignore MAS  spaces:  2-1’,
     ‘ignore MAS   spaces:  2+0’,
     ‘ignore MAS    spaces:  2+1’])

test(‘Equivalent whitespace characters.’,
    [‘Equiv.  spaces:     3-3’,
     "Equiv. \rspaces:    3-2",
     "Equiv. \x0cspaces:  3-1",
     "Equiv. \x0bspaces:  3+0",
     "Equiv. \nspaces:    3+1",
     "Equiv. \tspaces:    3+2"])

test(‘Case Independent sort.’,
    [‘cASE INDEPENDENT:  3-2’,
     ‘caSE INDEPENDENT:  3-1’,
     ‘casE INDEPENDENT:  3+0’,
     ‘case INDEPENDENT:  3+1’])

test(‘Numeric fields as numerics.’,
    [‘foo100bar99baz0.txt’,
     ‘foo100bar10baz0.txt’,
     ‘foo1000bar99baz10.txt’,
     ‘foo1000bar99baz9.txt’])

test(‘Title sorts.’,
    [‘The Wind in the Willows’,
     ‘The 40th step more’,
     ‘The 39 steps’,
     ‘Wanda’])


use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use sorter : script "Custom Iterative Ternary Merge Sort" -- <https://macscripter.net/viewtopic.php?pid=194430#p194430>

on naturalSort(listOfText)
    -- Produce versions of the strings for sorting purposes, doctored to get round
    -- the situations AppleScript's comparison attributes don't handle naturally.
    script o
        property input : listOfText
        property doctored : {}
    end script
    set regex to current application's NSRegularExpressionSearch
    repeat with i from 1 to (count listOfText)
        set thisString to (current application's class "NSMutableString"'s stringWithString:(item i of o's input))
        -- AppleScript's 'ignoring white space' setting ignores ALL white space. So, since the existence of
        -- white space between words has to be considered, physically remove or alter any to be ignored.
        -- Firstly reduce runs of any type of white space to single 'space' characters.
        tell thisString to replaceOccurrencesOfString:("\\s++") withString:(space) options:(regex) range:({0, its |length|()})
        -- Then remove any leading and/or trailing spaces.
        tell thisString to replaceOccurrencesOfString:("^ | $") withString:("") options:(regex) range:({0, its |length|()})
        -- Move any instance of "The ", "A ", or "An " at the front of a string to the end assuming the string to be a title.
        -- This allows the article to act as a tie-breaker if necessary.
        tell thisString to replaceOccurrencesOfString:("^(?i)(The|An?) (.++)$") withString:("$2 $1") options:(regex) ¬
            range:({0, its |length|()})
        -- For the sake of this task, replace any instances of "ſ" or "ʒ" with "s".
        tell thisString to replaceOccurrencesOfString:("[\\u0292\\u017f]") withString:("s") options:(regex) ¬
            range:({0, its |length|()})
        set end of o's doctored to thisString as text
    end repeat

    -- Set AppleScript's string comparison attributes for the sort.
    -- Ligatures are always compared by their component characters and AppleScript has no setting to change this.
    -- 'Numeric strings' are runs of digit characters only.
    -- The white space, hyphens, and case settings here are the defaults,
    -- but are set explicitly in case this handler's called from a different setting.
    considering numeric strings, white space and hyphens but ignoring diacriticals, punctuation and case
        -- Sort items 1 thru -1 of the doctored strings, rearranging the original list in parallel.
        tell sorter to sort(o's doctored, 1, -1, {slave:{listOfText}})
    end considering

    return listOfText
end naturalSort

(* Tests: *)
-- Leading, trailing, and multiple white spaces ignored:
naturalSort({"  ignore superfluous spaces: 1-3", "ignore superfluous spaces: 1-1", "  ignore superfluous    spaces: 1-2", ¬
    "   ignore superfluous spaces: 1-4", "ignore superfluous spaces: 1-7", "ignore superfluous    spaces: 1-5   ", ¬
    "ignore superfluous   spaces: 1-6", "   ignore    superfluous     spaces: 1-8"})
--> {"ignore superfluous spaces: 1-1", "  ignore superfluous    spaces: 1-2", "  ignore superfluous spaces: 1-3", "   ignore superfluous spaces: 1-4", "ignore superfluous    spaces: 1-5   ", "ignore superfluous   spaces: 1-6", "ignore superfluous spaces: 1-7", "   ignore    superfluous     spaces: 1-8"}

-- All white space characters treated as equivalent:
naturalSort({"Equiv. spaces: 2-6", "Equiv." & return & "spaces: 2-5", "Equiv." & (character id 12) & "spaces: 2-4", ¬
    "Equiv." & (character id 11) & "spaces: 2-3", "Equiv." & linefeed & "spaces: 2-2", "Equiv." & tab & "spaces: 2-1"})
(* -->
{"Equiv.    spaces: 2-1", "Equiv.
spaces: 2-2", "Equiv.�spaces: 2-3", "Equiv.�spaces: 2-4", "Equiv.
spaces: 2-5", "Equiv. spaces: 2-6"}
*)

-- Case ignored. (The order would actually be the same with case considered,
-- because case only decides the issue when strings are otherwise identical.)
naturalSort({"cASE INDEPENDENT: 3-1", "caSE INDEPENDENT: 3-2", "CASE independent: 3-3", "casE INDEPENDENT: 3-4", ¬
    "case INDEPENDENT: 3-5"})
--> {"cASE INDEPENDENT: 3-1", "caSE INDEPENDENT: 3-2", "CASE independent: 3-3", "casE INDEPENDENT: 3-4", "case INDEPENDENT: 3-5"}

-- Numerics considered by number value:
naturalSort({"foo1000bar99baz10.txt", "foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz9.txt"})
--> {"foo100bar10baz0.txt", "foo100bar99baz0.txt", "foo1000bar99baz9.txt", "foo1000bar99baz10.txt"}

-- Title sort:
naturalSort({"The Wind in the Willows", "The 40th Step More", "A Matter of Life and Death", "The 39 steps", ¬
    "An Inspector Calls", "Wanda"})
--> {"The 39 steps", "The 40th Step More", "An Inspector Calls", "A Matter of Life and Death", "Wanda", "The Wind in the Willows"}

--> Diacriticals (and case) ignored:
naturalSort({"Equiv. " & (character id 253) & " accents: 6-1", "Equiv. " & (character id 221) & " accents: 6-3", ¬
    "Equiv. y accents: 6-4", "Equiv. Y accents: 6-2"})
--> {"Equiv. ý accents: 6-1", "Equiv. Y accents: 6-2", "Equiv. Ý accents: 6-3", "Equiv. y accents: 6-4"}

-- Ligatures:
naturalSort({(character id 306) & " ligatured", "of", "ij no ligature", (character id 339), "od"})
--> {"Ĳ ligatured", "ij no ligature", "od", "œ", "of"}

-- Custom "s" equivalents and Esszet (Esszet normalises to ss):"
naturalSort({"Start with an " & (character id 658) & ": 8-1", "Start with an " & (character id 383) & ": 8-2", ¬
    "Start with an " & (character id 223) & ": 8-3", "Start with an s: 8-4", "Start with an ss: 8-5"})
--> {"Start with an ʒ: 8-1", "Start with an ſ: 8-2", "Start with an s: 8-4", "Start with an ß: 8-3", "Start with an ss: 8-5"}


#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <wctype.h>
#include <string.h>
#include <locale.h>

typedef struct wstr {
	wchar_t *s;
	int n, alloc;
} wstr;

#define w_del(w) { free(w->s); free(w); }
#define forchars(i, c, w) for(i = 0, c = w->s[0]; i < w->n && c; c = w->s[++i])
wstr *w_new()
{
	wstr *w = malloc(sizeof(wstr));
	w->alloc = 1;
	w->n = 0;
	w->s = malloc(sizeof(wchar_t));
	w->s[0] = 0;
	return w;
}

void w_append(wstr *w, wchar_t c)
{
	int n = w->n + 1;
	if (n >= w->alloc) {
		w->alloc *= 2;
		w->s = realloc(w->s, w->alloc * sizeof(wchar_t));
	}
	w->s[w->n++] = c;
	w->s[w->n] = 0;
}

wstr *w_make(wchar_t *s)
{
	int i, len = wcslen(s);
	wstr *w = w_new();
	for (i = 0; i < len; i++) w_append(w, s[i]);
	return w;
}

typedef void (*wtrans_func)(wstr *, wstr *);
void w_transform(wstr *in, wtrans_func f)
{
	wstr t, *out = w_new();
	f(in, out);
	t = *in; *in = *out; *out = t;
	w_del(out);
}
#define transfunc(x) void w_##x(wstr *in, wstr *out)

transfunc(nocase) {
	int i;
	wchar_t c;
	forchars(i, c, in) w_append(out, towlower(c));
}

transfunc(despace) {
	int i, gotspace = 0;
	wchar_t c;
	forchars(i, c, in) {
		if (!iswspace(c)) {
			if (gotspace && out->n)
				w_append(out, L' ');
			w_append(out, c);
			gotspace = 0;
		} else	gotspace = 1;
	}
}

static const wchar_t *const tbl_accent[] = { /* copied from Raku code */
	L"Þ", L"TH", L"þ", L"th", L"Ð", L"TH", L"ð", L"th", L"À", L"A",
	L"Á", L"A", L"Â", L"A", L"Ã", L"A", L"Ä", L"A", L"Å", L"A", L"à",
	L"a", L"á", L"a", L"â", L"a", L"ã", L"a", L"ä", L"a", L"å", L"a",
	L"Ç", L"C", L"ç", L"c", L"È", L"E", L"É", L"E", L"Ê", L"E", L"Ë",
	L"E", L"è", L"e", L"é", L"e", L"ê", L"e", L"ë", L"e", L"Ì",
	L"I", L"Í", L"I", L"Î", L"I", L"Ï", L"I", L"ì", L"i", L"í",
	L"i", L"î", L"i", L"ï", L"i", L"Ò", L"O", L"Ó", L"O", L"Ô",
	L"O", L"Õ", L"O", L"Ö", L"O", L"Ø", L"O", L"ò", L"o", L"ó", L"o",
	L"ô", L"o", L"õ", L"o", L"ö", L"o", L"ø", L"o", L"Ñ", L"N", L"ñ", L"n",
	L"Ù", L"U", L"Ú", L"U", L"Û", L"U", L"Ü", L"U", L"ù", L"u", L"ú", L"u",
	L"û", L"u", L"ü", L"u", L"Ý", L"Y", L"ÿ", L"y", L"ý", L"y" };

static const wchar_t *const tbl_ligature[] = {
	L"Æ", L"AE", L"æ", L"ae", L"ß", L"ss",
	L"ﬄ", L"ffl", L"ﬃ", L"ffi", L"ﬁ", L"fi", L"ﬀ", L"ff", L"ﬂ", L"fl",
	L"ſ", L"s", L"ʒ", L"z", L"ﬆ", L"st", /* ... come on ... */
};

void w_char_repl(wstr *in, wstr *out, const wchar_t *const *tbl, int len)
{
	int i, j, k;
	wchar_t c;
	forchars(i, c, in) {
		for (j = k = 0; j < len; j += 2) {
			if (c != tbl[j][0]) continue;
			for (k = 0; tbl[j + 1][k]; k++)
				w_append(out, tbl[j + 1][k]);
			break;
		}
		if (!k) w_append(out, c);
	}
}

transfunc(noaccent) {
	w_char_repl(in, out, tbl_accent, sizeof(tbl_accent)/sizeof(wchar_t*));
}

transfunc(noligature) {
	w_char_repl(in, out, tbl_ligature, sizeof(tbl_ligature)/sizeof(wchar_t*));
}

static const wchar_t *const tbl_article[] = {
	L"the", L"a", L"of", L"to", L"is", L"it" };
#define N_ARTICLES sizeof(tbl_article)/sizeof(tbl_article[0])
transfunc(noarticle) {
	int i, j, n;
	wchar_t c, c0 = 0;
	forchars(i, c, in) {
		if (!c0 || (iswalnum(c) && !iswalnum(c0))) { /* word boundary */
			for (j = N_ARTICLES - 1; j >= 0; j--) {
				n = wcslen(tbl_article[j]);
				if (wcsncasecmp(in->s + i, tbl_article[j], n))
					continue;
				if (iswalnum(in->s[i + n])) continue;
				i += n;
				break;
			}
			if (j < 0) w_append(out, c);
		} else
			w_append(out, c);
		c0 = c;
	}
}

enum { wi_space = 0, wi_case, wi_accent, wi_lig, wi_article, wi_numeric };
#define WS_NOSPACE	(1 << wi_space)
#define WS_NOCASE	(1 << wi_case)
#define WS_ACCENT	(1 << wi_accent)
#define WS_LIGATURE	(1 << wi_lig)
#define WS_NOARTICLE	(1 << wi_article)
#define WS_NUMERIC	(1 << wi_numeric)
const wtrans_func trans_funcs[] = {
	w_despace, w_nocase, w_noaccent, w_noligature, w_noarticle, 0
};
const char *const flagnames[] = {
	"collapse spaces",
	"case insensitive",
	"disregard accent",
	"decompose ligatures",
	"discard common words",
	"numeric",
};

typedef struct { wchar_t* s; wstr *w; } kw_t;
int w_numcmp(const void *a, const void *b)
{
	wchar_t *pa = ((const kw_t*)a)->w->s, *pb = ((const kw_t*)b)->w->s;
	int sa, sb, ea, eb;
	while (*pa && *pb) {
		if (iswdigit(*pa) && iswdigit(*pb)) {
			/* skip leading zeros */
			sa = sb = 0;
			while (pa[sa] == L'0') sa++;
			while (pb[sb] == L'0') sb++;
			/* find end of numbers */
			ea = sa; eb = sb;
			while (iswdigit(pa[ea])) ea++;
			while (iswdigit(pb[eb])) eb++;
			if (eb - sb > ea - sa) return -1;
			if (eb - sb < ea - sa) return 1;
			while (sb < eb) {
				if (pa[sa] > pb[sb]) return 1;
				if (pa[sa] < pb[sb]) return -1;
				sa++; sb++;
			}

			pa += ea; pb += eb;
		}
		else if (iswdigit(*pa)) return 1;
		else if (iswdigit(*pb)) return -1;
		else {
			if (*pa > *pb) return 1;
			if (*pa < *pb) return -1;
			pa++; pb++;
		}
	}
	return (!*pa && !*pb) ? 0 : *pa ?  1 : -1;
}

int w_cmp(const void *a, const void *b)
{
	return wcscmp(((const kw_t*)a)->w->s, ((const kw_t*)b)->w->s);
}

void natural_sort(wchar_t **strings, int len, int flags)
{
	int i, j;
	kw_t *kws = malloc(sizeof(kw_t) * len);

	for (i = 0; i < len; i++) {
		kws[i].s = strings[i];
		kws[i].w = w_make(strings[i]);
		for (j = 0; j < wi_numeric; j++)
			if (flags & (1 << j) && trans_funcs[j])
				w_transform(kws[i].w, trans_funcs[j]);
	}

	qsort(kws, len, sizeof(kw_t), (flags & WS_NUMERIC) ? w_numcmp : w_cmp);
	for (i = 0; i < len; i++) {
		w_del(kws[i].w);
		strings[i] = kws[i].s;
	}
	free(kws);
}

const wchar_t *const test[] = {
	L" 0000098 nina", L"100 niño", L"99 Ninja", L"100 NINA",
	L" The work is so diﬃcult to do it took ſome 100 aeons.  ",
	L"The work is so difficult it took some 100 aeons.",
	L"  The work is so diﬃcult   it took ſome 99 æons.  ",
};
#define N_STRINGS sizeof(test)/sizeof(*test)

void test_sort(int flags)
{
	int i, j;
	const wchar_t *str[N_STRINGS];
	memcpy(str, test, sizeof(test));

	printf("Sort flags: (");
	for (i = 0, j = flags; j; i++, j >>= 1)
		if ((j & 1))
			printf("%s%s", flagnames[i], j > 1 ? ", ":")\n");

	natural_sort((wchar_t **)str, N_STRINGS, flags);

	for (i = 0; i < N_STRINGS; i++)
		printf("%ls\n", str[i]);
	printf("\n");
}

int main()
{
	setlocale(LC_CTYPE, "");

	test_sort(WS_NOSPACE);
	test_sort(WS_NOCASE);
	test_sort(WS_NUMERIC);
	test_sort(WS_NOARTICLE|WS_NOSPACE);
	test_sort(WS_NOCASE|WS_NOSPACE|WS_ACCENT);
	test_sort(WS_LIGATURE|WS_NOCASE|WS_NOSPACE|WS_NUMERIC|WS_ACCENT|WS_NOARTICLE);

	return 0;
}


import std.stdio, std.string, std.algorithm, std.array, std.conv,
    std.ascii, std.range;

string[] naturalSort(string[] arr) /*pure @safe*/ {
    static struct Part {
        string s;

        int opCmp(in ref Part other) const pure {
            return (s[0].isDigit && other.s[0].isDigit) ?
                cmp([s.to!ulong], [other.s.to!ulong]) :
                cmp(s, other.s);
        }
    }

    static mapper(in string txt) /*pure nothrow @safe*/ {
        auto r = txt
                 .strip
                 .tr(whitespace, " ", "s")
                 .toLower
                 .chunkBy!isDigit
                 .map!(p => Part(p.text))
                 .array;
        return (r.length > 1 && r[0].s == "the") ? r.dropOne : r;
    }

    return arr.schwartzSort!mapper.release;
}

void main() /*@safe*/ {
    const tests = [
        // Ignoring leading spaces.
        ["ignore leading spaces: 2-2", " ignore leading spaces: 2-1", "
     ignore leading spaces: 2+1", "  ignore leading spaces: 2+0"],

        // Ignoring multiple adjacent spaces (m.a.s).
        ["ignore m.a.s spaces: 2-2", "ignore m.a.s  spaces: 2-1",
         "ignore m.a.s   spaces: 2+0", "ignore m.a.s    spaces: 2+1"],

        // Equivalent whitespace characters.
        ["Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2",
         "Equiv.\x0cspaces: 3-1", "Equiv.\x0bspaces: 3+0",
         "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"],

        // Case Indepenent [sic] sort.
        ["cASE INDEPENENT: 3-2" /* [sic] */, "caSE INDEPENENT: 3-1" /* [sic] */,
         "casE INDEPENENT: 3+0" /* [sic] */, "case INDEPENENT: 3+1" /* [sic] */],

        // Numeric fields as numerics.
        ["foo100bar99baz0.txt", "foo100bar10baz0.txt",
         "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"],

        // Title sorts.
        ["The Wind in the Willows", "The 40th step more",
         "The 39 steps", "Wanda"]];

    void printTexts(Range)(string tag, Range range) {
        const sic = range.front.canFind("INDEPENENT") ? " [sic]" : "";
        writefln("\n%s%s:\n%-(  |%s|%|\n%)", tag, sic, range);
    }

    foreach (test; tests) {
        printTexts("Test strings", test);
        printTexts("Normally sorted", test.dup.sort());
        printTexts("Naturally sorted", test.dup.naturalSort());
    }
}


defmodule Natural do
  def sorting(texts) do
    Enum.sort_by(texts, fn text -> compare_value(text) end)
  end

  defp compare_value(text) do
    text
    |> String.downcase
    |> String.replace(~r/\A(a |an |the )/, "")
    |> String.split
    |> Enum.map(fn word ->
         Regex.scan(~r/\d+|\D+/, word)
         |> Enum.map(fn [part] ->
              case Integer.parse(part) do
                {num, ""} -> num
                _         -> part
              end
            end)
       end)
  end

  def task(title, input) do
    IO.puts "\n#{title}:"
    IO.puts "< input >"
    Enum.each(input, &IO.inspect &1)
    IO.puts "< normal sort >"
    Enum.sort(input) |> Enum.each(&IO.inspect &1)
    IO.puts "< natural sort >"
    Enum.sort_by(input, &compare_value &1) |> Enum.each(&IO.inspect &1)
  end
end

[{"Ignoring leading spaces",
  ["ignore leading spaces: 2-2",   " ignore leading spaces: 2-1",
   "  ignore leading spaces: 2+0", "   ignore leading spaces: 2+1"]},

 {"Ignoring multiple adjacent spaces (m.a.s)",
  ["ignore m.a.s spaces: 2-2",   "ignore m.a.s  spaces: 2-1",
   "ignore m.a.s   spaces: 2+0", "ignore m.a.s    spaces: 2+1"]},

 {"Equivalent whitespace characters",
  ["Equiv. spaces: 3-3",    "Equiv.\rspaces: 3-2", "Equiv.\x0cspaces: 3-1",
   "Equiv.\x0bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"]},

 {"Case Indepenent sort",
  ["cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1",
   "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1"]},

 {"Numeric fields as numerics",
  ["foo100bar99baz0.txt",   "foo100bar10baz0.txt",
   "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"]},

 {"Title sorts",
  ["The Wind in the Willows", "The 40th step more", "The 39 steps", "Wanda"]}
]
|> Enum.each(fn {title, input} -> Natural.task(title, input) end)