0

Hello I'm (battling) to learn Haskell. Please help solve this problem using Haskell and list comprehension.

Consider the list of numbers wirth defined as follows:

(i) 1 is a member of wirth.

(ii) If x is a member of wirth, then so are 2 × x + 1 and 3 × x + 1.

(iii) These are the only elements of wirth.

Give a definition of wirth which produces the elements in increasing order.

(Source: Haskell Exercises 4: ZF-expressions Antoni Diller 26 July 2011)

Here is my Haskell attempt

f l = f ([2*u+1 | u <- l ] ++ [3*u+1 | u <- l])

Which seems to produce an infinite loop. This never returns

take 1 (f [1])

I managed to solve this problem using C# both iteratively and recursively.

private static List<int> WirthIterative(int take)
{

  var done = new List<int>();
  var todo = new Queue<int>();
  todo.Enqueue(1);

  int count = 0;

  while (todo.Count > 0 && count < take)
  {
    count++;

    var next = todo.Dequeue();

    var a = 2 * next + 1;
    var b = 3 * next + 1;

    todo.Enqueue(a);
    todo.Enqueue(b);

    done.Add(next);
  }

  done.Sort();
  return done;

}


private static List<int> WirthRecursive(int take)
{
  var result = new List<int>();
  _WirthRecursive(1, 0);
  result.Sort();
  return result;

  void _WirthRecursive(int member, int i)
  {
    if (i >= take) { return; }
    var a = 2 * member + 1;
    var b = 3 * member + 1;
    _WirthRecursive(a, i + 1);
    _WirthRecursive(b, i + 1);
    result.Add(member);
  }
}
vixiraw
  • 11
  • 1
  • I'm not sure that's a helpful duplicate. – chepner Dec 04 '20 at 20:15
  • @chepner The linked duplicate question begins with a code snippet that can be trivially adapted to produce the wirth numbers. This question gets answered before you even get to the answers. – Daniel Wagner Dec 05 '20 at 15:52
  • Given the OP's initial attempt, it's not clear they will *recognize* that the answer is in the question (though they may now). – chepner Dec 05 '20 at 16:09

0 Answers0