Hailstone sequence: Difference between revisions

Content added Content deleted
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 and two = Int 2 and three = Int 3 in
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 =
g [ ] (Int n);;
if x =/ one
then x::s
else g (x::s) (if mod_num x two =/ one
then three */ x +/ one
else x // two)
in
g [] (Int n)
;;


(* compute only sequence length *)
(* compute only sequence length *)
let haillen n =
let haillen n =
let one = Int 1 and two = Int 2 and three = Int 3 in
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 =
g 0 (Int n);;
if x =/ one
then s+1
else g (s+1) (if mod_num x two =/ one
then three */ x +/ one
else x // two)
in
g 0 (Int n)
;;


(* 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 0 -> (idx, len) | i ->
let rec g idx len = function
| 0 -> (idx, len)
let a = haillen i in
| i ->
if a > len then g i a (i-1) else g idx len (i-1) in
let a = haillen i in
g 0 0;;
if a > len
then g i a (i-1)
else g idx len (i-1)
in
g 0 0
;;


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 =