Loops/Increment loop index within loop body: Difference between revisions

m
(→‎{{header|Ruby}}: Use prime standard library)
Line 1,976:
=={{header|Haskell}}==
No index mutations or loops. Recursion is used.
<lang haskell>import Data.List (intercalate, unfoldr)
import Control.Monad (guard)
 
isPrime :: Int -> Bool
Line 1,983 ⟶ 1,984:
| n `mod` 2 == 0 || n `mod` 3 == 0 = False
| otherwise = l2 5 n
where l2 d n = x > n || l3 d n
l2 d n = (x > n)where ||x l3= d n* d
where l3 d n
x = d * | n `mod` d == 0 = False
l3 d | n `mod` (d + 2) == 0 = False
| n `mod` d == 0 | otherwise = Falsel2 (d + 6) n
| n `mod` (d + 2) == 0 = False
| otherwise = l2 (d + 6) n
 
showPrime :: Int -> Int -> [(Int, Int)]
showPrime i n = if isPrime i
| isPrime i = then (n, i) : showPrime (i + i) (n + 1)
| otherwise = else showPrime (i + 1) n
 
digitGroup :: Int -> String
digitGroup = intercalate "," . reverse . map show . digitsunfoldr (\n -> guard (n /= 0) >> pure (n `mod` 1000, n `div` 1000))
where
go n
| 0 == n = Nothing
| otherwise = Just (n `mod` 1000, n `div` 1000)
digits = unfoldr go
 
display :: (Int, Int) -> String
display (i, p) = show i ++ " " ++ digitGroup p
 
main = mapM_ (putStrLn . display) ($ take 42 ($ showPrime 42 1))</lang>
main :: IO ()
main = mapM_ (putStrLn . display) (take 42 (showPrime 42 1))</lang>
{{out}}
<pre>
Anonymous user