Consecutive primes with ascending or descending differences: Difference between revisions

Content added Content deleted
m (→‎{{header|Haskell}}: Removed a typo (trailing W prevented compilation after `primes`) added explicit module import)
m (→‎{{header|Haskell}}: Specified import expression)
Line 478: Line 478:
=={{header|Haskell}}==
=={{header|Haskell}}==
Uses prime generator implemented in the [[Sieve_of_Eratosthenes#Improved_efficiency_Wheels]].
Uses prime generator implemented in the [[Sieve_of_Eratosthenes#Improved_efficiency_Wheels]].
<lang haskell>import Data.Numbers.Primes
<lang haskell>import Data.Numbers.Primes (primes)


-- generates consecutive subsequences defined by given equivalence relation
-- generates consecutive subsequences defined by given equivalence relation
Line 484: Line 484:
where
where
go r [] = [r]
go r [] = [r]
go [] (h:t) = go [h] t
go [] (h : t) = go [h] t
go (y:ys) (h:t) | y `equiv` h = go (h:y:ys) t
go (y : ys) (h : t)
| otherwise = (y:ys) : go [h] t
| y `equiv` h = go (h : y : ys) t
| otherwise = (y : ys) : go [h] t

-- finds maximal values in a list and returns the first one
-- finds maximal values in a list and returns the first one
maximumBy g (h:t) = foldr f h t
maximumBy g (h : t) = foldr f h t
where
where f r x = if g r < g x then x else r
f r x = if g r < g x then x else r

-- the task implementation
-- the task implementation
task ord n = reverse $ p+s : p : (fst <$> rest)
task ord n = reverse $ p + s : p : (fst <$> rest)
where
where
(p,s):rest = maximumBy length
(p, s) : rest =
maximumBy length $
$ consecutives (\(_,a) (_,b) -> a `ord` b)
$ differences
consecutives (\(_, a) (_, b) -> a `ord` b) $
$ takeWhile (< n) primes
differences $
takeWhile (< n) primes
differences l = zip l $ zipWith (-) (tail l) l</lang>
differences l = zip l $ zipWith (-) (tail l) l</lang>