[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Any SML coders able to translate this to Python?


Marko Rauhamaa <marko at pacujo.net>:

>     def f(n):
>         def auxf1(sum, m, i):
>             if i == n:
>                 return sum
>             else:
>                 def auxf2(sum, m, i):
>                     if sum % m == 0:
>                         return auxf1(sum, m + 1, i)
>                     else:
>                         return auxf1(sum, m, i)
>                 return auxf2(sum + m * i, m, i + 1)
>         return auxf1(0, 1, 0)
>
> cheating slightly with locally named functions.
>
> If cheating is not allowed, you will need a Y combinator construct...

... and here's the same function without cheating:

    f = (lambda n:
         (lambda auxf1, auxf2: auxf1(auxf1, auxf2, 0, 1, 0))(
             lambda auxf1, auxf2, sum, m, i:
             sum
             if i == n else
             auxf2(auxf1, auxf2, sum + m * i, m, i + 1),
             lambda auxf1, auxf2, sum, m, i:
             auxf1(auxf1, auxf2, sum, m + 1, i)
             if sum % m == 0 else
             auxf1(auxf1, auxf2, sum, m, i)))

... or replacing the conditional with arrays:

    f = (lambda n:
         (lambda auxf1, auxf2: auxf1(auxf1, auxf2, 0, 1, 0))(
             lambda auxf1, auxf2, sum, m, i:
             [lambda m: auxf2(auxf1, auxf2, sum + m * i, m, i + 1),
              lambda m: sum][i == n](m),
             lambda auxf1, auxf2, sum, m, i:
             [lambda m: auxf1(auxf1, auxf2, sum, m, i),
              lambda m: auxf1(auxf1, auxf2, sum, m + 1, i)][sum % m == 0](m)))

It is possible to get rid of the arrays and numbers, too. Combinatory
logic would allow us to get rid of the local variables. At the pinnacle
of functional programming is iota:

   <URL: https://en.wikipedia.org/wiki/Iota_and_Jot>

The iota programming language has only one primitive value, the
Swiss-army-knife function ?, which can express Life, Universe and
Everything:

    ? = lambda f: (f(lambda x: lambda y: lambda z: (x(z))(y(z))))(
        lambda q: lambda i: q)


Marko