5 people like it.

Functional and simple version for Collatz Conjecture or 3n + 1 Problem

Functional and simple version for Collatz Conjecture or 3n + 1 Problem

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
//https://en.wikipedia.org/wiki/Collatz_conjecture
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36

let min a b = if (a > b) then b else a
let max a b = if (b > a) then b else a
let f a b =
  let g j =
    seq { 
      let mutable i = j
      while (i > 1) do
        yield i
        i <- if ((i % 2) = 0) then i / 2 else 3 * i + 1
      yield 1
    }
  seq{(min a b)..(max a b)} |> Seq.map g
let max_length a b = f a b |> Seq.map  (fun x -> x |> Seq.length) |> Seq.max
let print_all a b  = f a b |> Seq.iter (fun x -> printfn "%A" (x |> Seq.toList))

(*

> print_all 1 10;;
[1]
[2; 1]
[3; 10; 5; 16; 8; 4; 2; 1]
[4; 2; 1]
[5; 16; 8; 4; 2; 1]
[6; 3; 10; 5; 16; 8; 4; 2; 1]
[7; 22; 11; 34; 17; 52; 26; 13; 40; 20; 10; 5; 16; 8; 4; 2; 1]
[8; 4; 2; 1]
[9; 28; 14; 7; 22; 11; 34; 17; 52; 26; 13; 40; 20; 10; 5; 16; 8; 4; 2; 1]

> max_length 1 10;;
val it : int = 20
> max_length 100 200;;
val it : int = 125
> max_length 201 210;;
val it : int = 89
> max_length 900 1000;;
val it : int = 174

*)
val min : a:'a -> b:'a -> 'a (requires comparison)

Full name: Script.min
val a : 'a (requires comparison)
val b : 'a (requires comparison)
val max : a:'a -> b:'a -> 'a (requires comparison)

Full name: Script.max
val f : a:int -> b:int -> seq<seq<int>>

Full name: Script.f
val a : int
val b : int
val g : (int -> seq<int>)
val j : int
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
val mutable i : int
module Seq

from Microsoft.FSharp.Collections
val map : mapping:('T -> 'U) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.map
val max_length : a:int -> b:int -> int

Full name: Script.max_length
val x : seq<int>
val length : source:seq<'T> -> int

Full name: Microsoft.FSharp.Collections.Seq.length
val max : source:seq<'T> -> 'T (requires comparison)

Full name: Microsoft.FSharp.Collections.Seq.max
val print_all : a:int -> b:int -> unit

Full name: Script.print_all
val iter : action:('T -> unit) -> source:seq<'T> -> unit

Full name: Microsoft.FSharp.Collections.Seq.iter
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val toList : source:seq<'T> -> 'T list

Full name: Microsoft.FSharp.Collections.Seq.toList
Raw view New version

More information

Link:http://fssnip.net/7OI
Posted:1 year ago
Author:Fabio Galuppo
Tags: functional , seq