Search code examples
sequencesmlsmlnjmlsequences

Hofstadter Female and Male sequences in SML


This is my first SML program. I am trying to write a function that returns the first number to the nth number of Hofstadter's Female or Male sequence in list form. What I have so far is:

val m = fn (n) => if n = 0 then 1 :: [] else m f (n - 1);
val f = fn (n) => if n = 0 then 0 :: [] else f m (n - 1);

You can learn about the sequence here: https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Female_and_Male_sequences

The error that I am getting is:

[opening sequence.sml]
sequence.sml:1.49 Error: unbound variable or constructor: f
sequence.sml:1.47-1.58 Error: operator is not a function [tycon mismatch]
  operator: int list
  in expression:
    (m <errorvar>) (n - 1)
val it = () : unit

How can I correct this?


Solution

  • I ended up taking this approach:

    fun
        m (n) = if n = 0 then 0 else n - (f (m (n - 1)))
    and
        f (n) = if n = 0 then 1 else n - (m (f (n - 1)));
    val seq = fn n => List.tabulate((n), f);
    

    It is quite slow. If anybody has a faster version, then I'd love to see it.