I am learning F # (second day O :-)), and I want to create a Collatz sequence where each value is calculated based on Previous. I know ho do it in C #
public static void Main(string[] args)
{
Console.WriteLine(string.Join(", ", collatz(13)));
}
static IEnumerable<int> collatz(int n)
{
while (n != 1)
{
yield return n;
if (n % 2 == 0)
n /= 2;
else
n = 3 * n + 1;
}
yield return 1;
}
or how to create such an array in F #
let rec collatz = function
| 1 -> [ 1 ]
| n when n % 2 = 0 -> n::collatz (n / 2)
| n -> n::collatz (3 * n + 1)
collatz 13 |> Seq.map string |> String.concat ", " |> printfn "%s"
but don’t figure out the solution to the sequence ...
source
share