将字符串转换为整数。哈斯克尔

时间:2016-03-10 20:32:36

标签: haskell

由于我是Haskell和一般功能程序员的初学者,我想有人告诉我如何改进我的解决方案。任务是将字符串转换为整数。例如:

"sada21321" -> []
"d123 32 4 123.3    32 " -> [32, 4, 32]
"FFFFFFFFFF" -> []
"      " -> []

解决方案:

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)) 

2 个答案:

答案 0 :(得分:3)

您应该查看using (MyDBContext ctx = new MyDBContext()) { Person myPerson = ctx.First(x => x.Name == "frank"); // Do work with the non "work in progress" entities } using (MyWIPContext wipCtx = new MyWIPContext()) { Person myPerson = wipCtx.First(x => x.Name == "frank"); // Do work with the "work in progress" entites // If I need to move this entity to non "Work in Progress" maybe do: ctx.Attach(myPerson); ctx.SaveChanges(); // Where ctx is the non "Work in Progress context" } words函数。

(因为这是一项任务,我将让您填写详细信息)

答案 1 :(得分:0)

使用read ("Your string here.") :: Integer并检查read。您可以将字符串转换为大多数您想要的类型。