ninetynine-1.3.0: Ninety-Nine Haskell Problems
CopyrightCopyright (C) 2022 Yoo Chung
LicenseGPL-3.0-or-later
Maintainerdev@chungyc.org
Safe HaskellSafe-Inferred
LanguageGHC2021

Problems.P78

Description

Part of Ninety-Nine Haskell Problems. Some solutions are in Solutions.P78.

Synopsis

Documentation

collatz :: Integral a => a -> a Source #

Starting from a positive integer \(n\), we can have a sequence of numbers such that at each step, the next number is \(3n+1\) if \(n\) is odd, or \(\frac{n}{2}\) if \(n\) is even. The Collatz conjecture states that this sequence will always end at 1 after a finite number of steps.

Using the Writer monad, count the number of these steps for a given positive integer \(n\).

Examples

>>> collatz 1
0
>>> collatz 2
1
>>> collatz 31
106

Hint

Expand

The outputs produced by tell with the Writer monad are combined with mappend. In the Sum monoid, mappend is addition.