Skip to content

Instantly share code, notes, and snippets.

@fayazkhan
Last active September 17, 2017 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fayazkhan/7a8147cfded7ed8fa0b2920b9f9f3649 to your computer and use it in GitHub Desktop.
Save fayazkhan/7a8147cfded7ed8fa0b2920b9f9f3649 to your computer and use it in GitHub Desktop.
Solution to SDS challenge 4
import Data.Char
import Data.List
import Text.Read
main = do
putStrLn "Number"
number <- getLine
putStrLn "Number of digits to multiply"
digits <- getLine
putStrLn $ pureMain digits number
pureMain digitsString numberString = let
maybeNumberList = stringToIntList numberString
maybeDigits = readMaybe digitsString
in case largestProduct maybeDigits maybeNumberList of
Right value -> "Largest product\n" ++ show value
Left message -> message
largestProduct :: Maybe Int -> Maybe [Int] -> Either String Int
largestProduct _ Nothing = Left "Invalid number."
largestProduct Nothing _ = Left "Invalid digits."
largestProduct (Just digits) _
| digits < 1 = Left "Digits must be a positive integer."
largestProduct (Just digits) (Just numberList) = let
numberListRepetitions = take digits (tails numberList)
in case products numberListRepetitions of
[] -> Left "Number does not have as many digits."
productList -> Right (maximum productList)
products :: [[Int]] -> [Int]
products [] = []
products [singleList] = singleList
products (firstList:restOfLists) = zipWith (*) firstList (products restOfLists)
stringToIntList :: String -> Maybe [Int]
stringToIntList "" = Nothing
stringToIntList [character]
| isDigit character = Just [digitToInt character]
| otherwise = Nothing
stringToIntList (first:restOfString) = let
maybeFirstInt = stringToIntList [first]
maybeRestofInts = stringToIntList restOfString
in case (maybeFirstInt, maybeRestofInts) of
(Just [firstInt], Just restOfInts) -> Just (firstInt:restOfInts)
_ -> Nothing
@fayazkhan
Copy link
Author

Build steps:
ghc euler8.hs && ./euler8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment