在haskell编程中拆分字符串

时间:2017-08-09 09:25:29

标签: haskell

嗨我正在尝试做一个函数输入是一个字符串列表,输出再次是输入中出现的所有单词的列表。

例如输入[“例如,”,“爱”,“讨厌。”] 输出[“For”,“example”,“love”,“hate”]

我有这个。任何帮助,将不胜感激。另外,我如何只用一个函数和线性时间删除空格? 而不是使用任何现有的功能

split' :: String -> [String]
split' [] = []
split' (x:xs)
     | isBlank x = split' xs
     | otherwise = waitForBlank (x:xs) : split' (drop (length (waitForBlank (x:xs))) xs)

isBlank :: Char -> Bool
isBlank x = if x == ' ' then True else False

waitForBlank :: String -> String
waitForBlank [] = []
waitForBlank (x:xs)
     | isBlank x = []
     | otherwise = x : waitForBlank xs

1 个答案:

答案 0 :(得分:4)

有一个很酷的单行来执行你需要的东西

["For example,", "love,", "hate."] >>= words

>>=具有类型(>>=) :: Monad m => m a -> (a -> m b) -> m b,它接受​​一个返回monadic结构的函数,并将结果连接到monadic结构中。

如果您想自己实施words

words' xs =
  let
    waitForBlank (acc, buff) [] = (acc ++ [buff], buff)
    waitForBlank (acc, buff) (x:xs) =
      if x == ' ' then
        waitForBlank (acc ++ [buff], []) xs
      else
        waitForBlank (acc, buff ++ [x]) xs
  in
    fst (waitForBlank ([], []) xs)

或者使用(:)reverse结果(为了获得更好的效果):

words'' xs =
  let
    waitForBlank (acc, buff) [] = (reverse (buff : acc), buff)
    waitForBlank (acc, buff) (x:xs) =
      if x == ' ' then
        waitForBlank ((reverse buff) : acc, []) xs
      else
        waitForBlank (acc, x:buff) xs
  in
    fst (waitForBlank ([], []) xs)