Hailstone sequence: Difference between revisions
Content deleted Content added
m →{{header|OCaml}}: num_of_int x -> Int x, more readable |
m →{{header|OCaml}}: indentation |
||
Line 214: | Line 214: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
<lang ocaml> |
<lang ocaml>#load "nums.cma";; |
||
#load "nums.cma";; |
|||
open Num;; |
open Num;; |
||
(* generate Hailstone sequence *) |
(* generate Hailstone sequence *) |
||
let hailstone n = |
let hailstone n = |
||
let one = Int 1 |
let one = Int 1 |
||
and two = Int 2 |
|||
let rec g s x = if x =/ one then x::s else |
|||
and three = Int 3 in |
|||
g (x::s) (if mod_num x two =/ one then three */ x +/ one else x // two) in |
|||
let rec g s x = |
|||
⚫ | |||
if x =/ one |
|||
then x::s |
|||
else g (x::s) (if mod_num x two =/ one |
|||
then three */ x +/ one |
|||
else x // two) |
|||
in |
|||
⚫ | |||
;; |
|||
(* compute only sequence length *) |
(* compute only sequence length *) |
||
let haillen n = |
let haillen n = |
||
let one = Int 1 |
let one = Int 1 |
||
and two = Int 2 |
|||
let rec g s x = if x =/ one then s+1 else |
|||
and three = Int 3 in |
|||
g (s+1) (if mod_num x two =/ one then three */ x +/ one else x // two) in |
|||
let rec g s x = |
|||
⚫ | |||
if x =/ one |
|||
then s+1 |
|||
else g (s+1) (if mod_num x two =/ one |
|||
then three */ x +/ one |
|||
else x // two) |
|||
in |
|||
⚫ | |||
;; |
|||
(* max length for starting values in 1..n *) |
(* max length for starting values in 1..n *) |
||
let hailmax = |
let hailmax = |
||
let rec g idx len = function |
let rec g idx len = function |
||
| 0 -> (idx, len) |
|||
⚫ | |||
| i -> |
|||
⚫ | |||
⚫ | |||
⚫ | |||
if a > len |
|||
then g i a (i-1) |
|||
⚫ | |||
in |
|||
⚫ | |||
;; |
|||
hailmax 100000;; |
hailmax 100000 ;; |
||
(* - : int * int = (77031, 351) *) |
(* - : int * int = (77031, 351) *) |
||
List.rev_map string_of_num (hailstone 27);; |
List.rev_map string_of_num (hailstone 27) ;; |
||
(* - : string list = |
(* - : string list = |