0

I want to make my mutually recursive functions stack-safe, but because they have different signatures - one traverses a list and other a tree(?) of sorts - I'm not clear how to go about this.

Here's an Idris mwe. (I hope I've not rendered it trivial.)

data A : Type where
  AL : List A -> A
  A0 : A

data B : Type where
  BL : List B -> B
  B0 : B

mutual
  as2bs : List A -> List B
  as2bs [] = []
  as2bs (x :: xs) = a2b x :: as2bs xs

  a2b : A -> B
  a2b (AL as) = BL (as2bs as)
  a2b A0 = B0

I want the function a2b : A -> B.

I have tried using CPS, but I don't know how to coerce the standard approach to functions over different types.

It crossed my mind to create a single function as2bs, and extract the resulting B from an [a], but I need to know I get a single B from my single A, so that's not going to work (short of leveraging dependent types which are a last resort).

Extra helpful if you can comment on whether a solution exists even where the conversion A -> B might fail with a Maybe.

7
  • You're traversing a tree. You can't do that without a stack of some sort. Commented Nov 25 at 22:19
  • @Bergi could you elaborate? Does that mean I can't make it stack safe? Commented Nov 26 at 18:05
  • What exactly do you mean by "stack safe"? Which runtime are you even using? Commented Nov 26 at 20:52
  • @Bergi C, but I don't expect another to different. By "stack safe", I mean avoiding stack overflow - I think Commented Nov 26 at 22:21
  • You need a stack the size of the depth of your tree. If you want to avoid a stack overflow (and are using a runtime with a stack far smaller than the heap), put that stack on the heap instead of using the call stack for a recursive traversal. If the A and B trees fit in memory, so should that stack. Commented Nov 26 at 22:58

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.