Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/nwtgck/loop-to-tailrec
Convert a while-loop to a tail-recursive function
https://github.com/nwtgck/loop-to-tailrec
converter loop online tailrec
Last synced: about 1 month ago
JSON representation
Convert a while-loop to a tail-recursive function
- Host: GitHub
- URL: https://github.com/nwtgck/loop-to-tailrec
- Owner: nwtgck
- Created: 2017-03-14T10:23:01.000Z (almost 8 years ago)
- Default Branch: develop
- Last Pushed: 2018-12-20T00:17:35.000Z (about 6 years ago)
- Last Synced: 2024-10-11T15:10:54.575Z (3 months ago)
- Topics: converter, loop, online, tailrec
- Language: JavaScript
- Homepage: https://nwtgck.github.io/loop-to-tailrec
- Size: 785 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
loop-to-tailrec
==Convertor a while-loop to a tail-recursive function
# Page
http://nwtgck.github.io/loop-to-tailrec/
# Demo
![](./demo-images/demo1.gif)
# What is this?
Convert the following format while-loop to a tail-rec function!
# Example1 - Fibonacci
### Input (while-loop)
```scala
def fib ( n: Int ): Int = {
var i: Int = 0
var a: Int = 1
var b: Int = 1
while(i < n){
val newI = i+1
val newA = b
val newB = a+b
i = newI
a = newA
b = newB
}
a
}
```==>
### Output (tailrec)
```scala
// Scala(tailrec)
def fib ( n: Int ): Int = {
import scala.annotation.tailrec
@tailrec
def _fib( i: Int , a: Int , b: Int ): Int = {
if(i < n) _fib( i+1 , b , a+b )
else a
}
_fib( 0 , 1 , 1 )
}
```# Example2 - foldLeft
### Input (while-loop)
```scala
def foldLeft [ E , A ] ( seq: Seq[E] , zero: A , f: (A, E) => A ): A = {
var accum: A = zero
var i: Int = 0
while(i < seq.length){
val newAccum = f(accum, seq(i))
val newI = i + 1
accum = newAccum
i = newI
}
accum
}
```==>
### Output (tailrec)
```scala
// Scala(tailrec)
def foldLeft [ E , A ] ( seq: Seq[E] , zero: A , f: (A, E) => A ): A = {
import scala.annotation.tailrec
@tailrec
def _foldLeft( accum: A , i: Int ): A = {
if(i < seq.length) _foldLeft( f(accum, seq(i)) , i + 1 )
else accum
}
_foldLeft( zero , 0 )
}
```You can access http://nwtgck.github.io/loop-to-tailrec/ and try other examples!