字符串到 Int 列表

标签 string haskell int

我想将 Maybe [int] 合并到其中。

代码应该采用一个字符串并过滤掉空格,将其转换为整数列表,如果它们是字母,则返回 Nothing。

text2digits :: String -> [Int]
text2digits s = case s of
    []          -> []
    x:xs        
        |isDigit x      -> digitToInt x :text2digits (filter (/= ' ') xs)
        |otherwise      -> undefined

input "1233 5687"  output: [1,2,3,3,5,6,8,7]
input "a89"       required output : Nothing 
                  current output: undefined

我已经尝试过,但它显示了错误列表

text2digits :: String -> Maybe [Int]
text2digits s = case s of
    []          -> Just []
        x:xs        
        |isDigit x      -> Just digitToInt x :text2digits (filter (/= ' ') xs)
        |otherwise      -> Nothing

最佳答案

您为 text2digits :: String -> Maybe [Int] 指定的代码有什么问题? ?

问题出在这一行:

digitToInt x :text2digits (filter (/= ' ') xs)

text2digits返回值 Maybe [Int]类型,但是 (:)预计为[Int] .

为了修复它,您可以使用 fmap<$>将函数应用于仿函数内的结构 Maybe :

import Data.Char

text2digits :: String -> Maybe [Int]
text2digits s = case s of
    [] -> Just []
    x:xs
      |isDigit x      -> ((digitToInt x) :) <$> text2digits (filter (/= ' ') xs)
      |otherwise      -> Nothing

main = print $ text2digits "1233 5687"

或者您可以使用traverse稍微重构一下函数:

import Data.Char

text2digits :: String -> Maybe [Int]
text2digits s =
  traverse digitToMaybeInt $ filter (/= ' ') s
  where
    digitToMaybeInt x
      | isDigit x = Just $ digitToInt x
      | otherwise = Nothing

main = print $ text2digits "89"

关于字符串到 Int 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46357690/

相关文章:

date - 如何在 Haskell 中将日期转换为 Int

swift - 我怎样才能更正这段代码,同时让它更简单

C++ sizeof() 没有返回正确的大小

java - 如何将段落拆分成句子?

haskell - 在 Haskell 中并发读写 IOArray

c# - 将 double 转换为 int 返回意外结果

c - 将字符串解析为 int 数组 - 收到警告 "makes pointer from integer without a cast"

python - 在字符串中查找重复出现的模式

python - 如何在 Python 中将字符串转换为有效的变量名?

haskell - 如何在类型级别清空大小写