Stern-Brocot sequence: Difference between revisions

Content added Content deleted
m (→‎{{header|REXX}}: added/changed whitespace and comments, added checks to possibly bypass computing some of the tasks.)
m (→‎{{header|Haskell}}: Tidied iterate version.)
Line 2,436: Line 2,436:
Or, expressed in terms of iterate:
Or, expressed in terms of iterate:


<lang haskell>import Data.List (nubBy, sortBy)
<lang haskell>import Data.Function (on)
import Data.List (nubBy, sortOn)
import Data.Ord (comparing)
import Data.Ord (comparing)

import Data.Monoid ((<>))
------------------ STERN-BROCOT SEQUENCE -----------------
import Data.Function (on)


sternBrocot :: [Int]
sternBrocot :: [Int]
sternBrocot =
sternBrocot = head <$> iterate go [1, 1]
where
let go (a:b:xs) = (b : xs) <> [a + b, b]
in head <$> iterate go [1, 1]
go (a : b : xs) = (b : xs) <> [a + b, b]


-- TEST -------------------------------------------------------------
--------------------------- TEST -------------------------
main :: IO ()
main :: IO ()
main = do
main = do
Line 2,452: Line 2,453:
print $
print $
take 10 $
take 10 $
nubBy (on (==) fst) $
nubBy (on (==) fst) $
sortOn fst $
sortBy (comparing fst) $ takeWhile ((110 >=) . fst) $ zip sternBrocot [1 ..]
print $ take 1 $ dropWhile ((100 /=) . fst) $ zip sternBrocot [1 ..]
takeWhile ((110 >=) . fst) $
zip sternBrocot [1 ..]
print $ (all ((1 ==) . uncurry gcd) . (zip <*> tail)) $ take 1000 sternBrocot</lang>
print $
take 1 $
dropWhile ((100 /=) . fst) $
zip sternBrocot [1 ..]
print $
(all ((1 ==) . uncurry gcd) . (zip <*> tail)) $
take 1000 sternBrocot</lang>
{{Out}}
{{Out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]