【问题标题】:How do i syntax in haskell我如何在haskell中语法
【发布时间】:2019-09-15 09:23:07
【问题描述】:

我正在尝试编写一个函数,该函数接收一个字符串,然后将字符串作为字符串单词列表返回(如内置函数的单词),到目前为止我已经写了

ord :: String -> [String]
ord [] = []
ord xs = let
    ys = groupBy (\x y -> y /= ' ') xs
    in filter (not . null) ys

我认为这会消除列表中的空字符串,但我只得到这个输出

输入:

ord  “aa b       c   -    dd” 

输出:

["aa"," b"," "," "," "," "," "," "," c"," "," "," -"," "," "," "," dd"]

当这是我想要的输出时:

[“aa”, ”b”, ”c”, ”-“, ”dd”]

如果我尝试写,我会得到相同的结果

ord :: String -> [String]
ord [] = []
ord xs = filter (not . null) ys
    where
        ys = groupBy (\x y -> y /= ' ') xs

如何重新编写此代码,以便删除其空字符串列表? 还是使用正确的语法?我刚刚学习 Haskell,但语法仍然有问题......

【问题讨论】:

  • 这里的语法没有问题——编译器会告诉你的。重写代码以省略仅包含空格的字符串,并注意某些字符串以空格开头。
  • 如果你想用groupBy把所有的空间扔到他们自己的组里,你也需要看看x。否则,空格将与其后面的非空格组合在一起。 null 检查空字符串(零个字符),而不是空字符串(只有空格)。

标签: haskell


【解决方案1】:

我根本不会在这里打扰groupBy。特别是,没有必要为了扔掉它们而建立空间列表。让我们从一个删除初始空格然后将所有内容抓取到第一个空格的函数开始:

grab :: String -> (String, String)
grab = break isSpace . dropWhile isSpace

请注意,当且仅当xs 的所有元素都是空格时,grab xs 的第一个组件将为空。

现在我们可以写了

myWords :: String -> [String]
myWords xs = case grab xs of
  ([], _) -> []
  (beginning, end) -> beginning : myWords end

【讨论】:

    【解决方案2】:

    groupBy 表示你将xy 放在同一个组中,前提是条件满足。但是在这里你将两者组合在一起,因为y 不等于空格。

    因此,您可以更改分组谓词,并将 xy 放在同一个组中,前提是两者都是空格或非空格:

    import Data.Char(isSpace)
    
    ord :: String -> [String]
    ord [] = []
    ord xs = let
        ys = groupBy (\x y -> isSpace x == isSpace y) xs
        in filter (not . null) ys

    或更短:

    import Data.Char(isSpace)
    import Data.Function(on)
    
    ord :: String -> [String]
    ord [] = []
    ord xs = let
        ys = groupBy (on (==) isSpace) xs
        in filter (not . null) ys

    现在我们检索:

    Prelude Data.List> ord "aa b       c   -    dd"
    ["aa"," ","b","       ","c","   ","-","    ","dd"]
    

    我们当然还没有得到预期的结果。我们可以过滤掉只包含空格字符的字符串,而不是过滤掉空字符串:

    import Data.Char(isSpace)
    import Data.Function(on)
    
    ord :: String -> [String]
    ord [] = []
    ord xs = let
        ys = groupBy (on (==) isSpace) xs
        in filter (not . all isSpace) ys

    我们不需要手动转换空的情况,因为空列表上的groupBy会产生一个空列表,因此我们可以构造一个单行来进行处理:

    import Data.Char(isSpace)
    import Data.Function(on)
    
    ord :: String -> [String]
    ord = filter (not . all isSpace) . groupBy (on (==) isSpace)

    那么我们就得到了预期的结果:

    Prelude Data.List Data.Char> ord "aa b       c   -    dd"
    ["aa","b","c","-","dd"]
    

    【讨论】:

      猜你喜欢
      • 2015-03-09
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多