Zulip Chat Archive

Stream: general

Topic: Free general recursion


Trebor Huang (Oct 07 2023 at 11:43):

I made a quick Lean implementation of McBride's paper *Turing Completeness Totally Free*, which essentially treats general recursion as a side effect, wrapping it in a monad. Combined with the unchained do notation I find it very powerful. Perhaps we can replace some partial definition with these, so that we can reason about them.

TL; DR:

/-- Unsafe execution of general recursive function. -/
unsafe def execute (f : (s : S)  T s) (s : S) : T s

/- Example: Counting how many triplings are needed to put a number to 1
  step 1 = 0
  step k = step (k/2)       (k even)
  step k = 1 + step (3k+1)  (k odd)
-/

def step : (_ : Nat)  Nat := fun n => do
  if n <= 1 then
    return 0
  else if n % 2 = 0 then
    call (n / 2)  -- `call` represents the recursing function
  else
    return 1 + ( call (3 * n + 1))

-- Starting from 17, we need three triplings:
--  17 -> 52 ... 13 -> 40 ... 5 -> 16 ... 1
#eval execute step 17  -- 3

Trebor Huang (Oct 07 2023 at 11:44):

Full Code

Trebor Huang (Oct 07 2023 at 11:47):

A few questions:

  • How can I solve that universe level issue in the middle? Writing the most general level seems to interfere with monad typeclass interference? (Or I messed up when calculating the levels)
  • Can this be easily combined with the do notation so general recursion compiles to this monad?
  • Is programming like this actually practical?

Eric Wieser (Oct 08 2023 at 20:46):

I think the universe weirdness is unavoidable, and it's a consequence of the monad framework (and as a result, do notation) not being (maximally) universe-polymorphic

Eric Wieser (Oct 08 2023 at 20:46):

Which is to say; there is no Monad.bind that can move from one universe to another.

Eric Wieser (Oct 08 2023 at 20:47):

But this has been discussed a bunch before in other threads

Ioannis Konstantoulas (Oct 09 2023 at 13:51):

Eric Wieser said:

But this has been discussed a bunch before in other threads

Unfortunately, thread discoverability is an issue, especially to new people who do not know what the right search keywords are. There are also no tags like in Q&A sites, and, honestly, Zulip search is slow (actually, Zulip is unusable on my Samsung phone).

Eric Wieser (Oct 09 2023 at 14:07):

Zulip search is very bad on mobile, but works on on desktop

Eric Wieser (Oct 09 2023 at 14:08):

Eric Wieser said:

Here's a discussion about changing the typeclasses to achieve that in Lean 3, and one about universe-polymorphic IO in Lean 4.


Last updated: Dec 20 2023 at 11:08 UTC