Last active
September 17, 2017 12:16
-
-
Save fayazkhan/7a8147cfded7ed8fa0b2920b9f9f3649 to your computer and use it in GitHub Desktop.
Solution to SDS challenge 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Build steps:
ghc euler8.hs && ./euler8