on master help sign in
String to Int function. #2639
38b08c5Saurabh Rawat
libs/prelude/Prelude/Strings.idr+15
@@ -340,6 +340,20 @@ toUpper x with (strM x)
340 strToLower (strCons c cs) | (StrCons c cs) =
340 strToLower (strCons c cs) | (StrCons c cs) =
341 strCons (toUpper c) (toUpper (assert_smaller (strCons c cs) cs ))
341 strCons (toUpper c) (toUpper (assert_smaller (strCons c cs) cs ))
342
342
343+||| Convert a number string to int.
344+|||
345+||| ```idris example
346+||| parseInt "123"
347+||| ```
348+parseInt : String -> Maybe Int
349+parseInt s with (strM s)
350+ parseInt "" | StrNil = Nothing
351+ parseInt (strCons x xs) | (StrCons x xs) = parseIntAux (unpack xs) (ord x - 48) where
352+ parseIntAux : (List Char) -> Int -> Maybe Int
353+ parseIntAux [] acc = Just acc
354+ parseIntAux (c :: cs) acc = if (c >= '0' && c <= '9') then parseIntAux cs ((acc * 10) + (ord c) - 48)
355+ else Nothing
356+
343--------------------------------------------------------------------------------
357--------------------------------------------------------------------------------
344-- Predicates
358-- Predicates
345--------------------------------------------------------------------------------
359--------------------------------------------------------------------------------
@@ -365,3 +379,4 @@ nullStr : String -> IO Bool
365nullStr p = do ok <- foreign FFI_C "isNull" (String -> IO Int) p
379nullStr p = do ok <- foreign FFI_C "isNull" (String -> IO Int) p
366 return (ok /= 0)
380 return (ok /= 0)
367
381
382+