Monday, May 27, 2013

F# Sequence for Collatz Problem

F# Sequence for Collatz Problem is:
let collatzSeq n =
  let collatzFunction n =
    match n % 2L with
    | 0L -> n / 2L
    | _ -> 3L * n + 1L
  let rec collatzCalc n accum =
    let accum'next = Seq.append accum <| Seq.singleton n
    if n = 1L then
      accum'next
    else
      collatzCalc <| collatzFunction n <| accum'next
  match n > 0L with
  | true -> collatzCalc n Seq.empty<int64>
  | _ -> failwith "The argument should be a natural number."
> collatzSeq 1L;;
val it : seq<int64> = seq [1L]
> collatzSeq 2L;;
val it : seq<int64> = seq [2L; 1L]
> collatzSeq 3L |> Seq.toList;;
val it : int64 list = [3L; 10L; 5L; 16L; 8L; 4L; 2L; 1L]
> collatzSeq 4L |> Seq.toList;;
val it : int64 list = [4L; 2L; 1L]
> collatzSeq 5L |> Seq.toList;;
val it : int64 list = [5L; 16L; 8L; 4L; 2L; 1L]
> collatzSeq 6L |> Seq.toList;;
val it : int64 list = [6L; 3L; 10L; 5L; 16L; 8L; 4L; 2L; 1L]
> collatzSeq 7L |> Seq.toList;;
val it : int64 list =
  [7L; 22L; 11L; 34L; 17L; 52L; 26L; 13L; 40L; 20L; 10L; 5L; 16L; 8L; 4L; 2L; 1L]

No comments:

Post a Comment