Reputation: 5073
Because of the fact I am a beginner when it comes to Haskell and generally functional programmer I would like to someone tell me how to improve my solution. The task is convert string to ints. For example:
"sada21321" -> []
"d123 32 4 123.3 32 " -> [32, 4, 32]
"FFFFFFFFFF" -> []
" " -> []
Solution:
import Data.Char
readInts :: String -> [Int]
readInts s = (( map convertStringToInt ) . (filter (\ elem -> (all isDigit elem))) . getSubstrings)s
getSubstrings :: String -> [String]
getSubstrings s = getSubstrings' s [] [] where
getSubstrings' (h:t) curr res
| h == ' ' && (length curr ) > 0 = getSubstrings' t [] ( res ++ [curr])
| h /= ' ' = getSubstrings' t (curr ++ [h]) res
| otherwise = getSubstrings' t curr res
getSubstrings' [] curr res = if (length curr ) > 0 then ( res ++ [curr] ) else res
reverseList :: [a] -> [a]
reverseList [] = []
reverseList (h:t) = (reverseList t) ++ [h]
convertStringToInt :: String -> Int
convertStringToInt s = convertStringToInt' (reverseList s) 1 0
where
convertStringToInt' [] _ res = res
convertStringToInt' (h:t) m res = convertStringToInt' t (m*10) (res + (((ord h) - 48)*m))
Upvotes: 0
Views: 145
Reputation: 9
Use read ("Your string here.") :: Integer
and also check for read
. You can convert string to mostly any types you want to.
Upvotes: 0
Reputation: 12070
You should take a look at the words
and read
functions.
(because this is an assignment, I'll let you fill in the details)
Upvotes: 3