Sum to 100: Difference between revisions
→{{header|Haskell}}: Replaced an arrow with an applicative, tidied.
No edit summary |
(→{{header|Haskell}}: Replaced an arrow with an applicative, tidied.) |
||
Line 2,796:
=={{header|Haskell}}==
<lang Haskell>import
import Data.Ord (comparing)▼
import Control.Arrow ((&&&))▼
import Data.Char (intToDigit)
import
( find,
group,
intercalate,
sort,
sortBy,
)
▲import Data.Ord (comparing)
data Sign
Line 2,808 ⟶ 2,814:
| Minus
deriving (Eq, Show)
------------------------ SUM TO 100 ----------------------
universe :: [[(Int, Sign)]]
universe =
zip [1 .. 9]
<$> filter
filter ((/= Plus) . head) (replicateM 9 [Unsigned, Plus, Minus])▼
((/= Plus) . head)
allNonNegativeSums :: [Int]
allNonNegativeSums =
sort $
filter
(>= 0)
(asSum <$> universe)
uniqueNonNegativeSums :: [Int]
Line 2,822 ⟶ 2,836:
asSum :: [(Int, Sign)] -> Int
asSum xs =
n
+ ( case s of
[] -> 0
_ -> read s :: Int
where
(n, s) = foldr readSign (0, []) xs
readSign ::
(Int, Sign) ->
(Int, String) ->
(Int, String)
readSign (i, x) (n, s)
| x == Unsigned = (n, intToDigit i : s)
| otherwise =
( ( case x of
Plus -> (+)
_ -> (-
)
n
(read (show i <> s) :: Int),
)
asString :: [(Int, Sign)] -> String
Line 2,845 ⟶ 2,865:
| x == Unsigned = intToDigit i : s
| otherwise =
( case x of
Plus -> " +"
_ -> " -"
<> s
--------------------------- TEST -------------------------
main :: IO ()
main =
putStrLn $
unlines
[ "Sums to 100:",
unlines
▲ , show
10
, maybeReport (find (uncurry (/=)) (zip [0 ..] uniqueNonNegativeSums))▼
( sortBy
, "\n10 largest sums:"▼
(group allNonNegativeSums)
▲ ]
)
),
"\nFirst positive integer not expressible "
<> "as a sum of this kind:",
maybeReport
( find
(uncurry (/=))
),
show
( take
10
( sortBy
(flip compare)
uniqueNonNegativeSums
)
)
]
where
maybeReport ::
String
maybeReport (Just (x, _)) = show x
maybeReport _ = "No gaps found"</lang>
|