【问题标题】:Create a function that takes a string (some sentence) and split it into list of tuples (word, length word)创建一个接受字符串(某个句子)并将其拆分为元组列表(单词,长度单词)的函数
【发布时间】:2022-01-01 03:19:03
【问题描述】:

创建一个函数,该函数接受一个字符串并将其拆分为列表 (word, length word) 类型的元组。它需要使用 foldr 遍历列表,不使用 length 和/或 (++).

例如

> splitSen "    Asdf  qw   zx     mn      "
[("Asdf",4),("qw",2),("zx",2),("mn",2)]

我的实现是这样的

splitSen :: String -> [(String,Int)]
splitSen cs = foldr func [] cs where
  func ' ' ((c1,n1) : ps) = ps
  func c ((c1,n1) : ps) = (c:c1,1+n1):ps

我得到一个错误

*** 例外:函数 func 中的非详尽模式

但无法弄清楚我缺少什么模式。

【问题讨论】:

    标签: string list haskell fold


    【解决方案1】:

    以防有人在这里有类似的东西我设法做

    splitSen = fst . foldr func ([], True) where
      func ' ' ([], _) = ([], True)
      func c ([],bool) | bool = ([([c],1)], False)
      func ' ' (((word, len):rest), bool) = (((word, len):rest), True)
      func c (y@((word, len):rest), bool) | bool = (([c],1):y, False) 
                        | otherwise = (((c:word, 1+len):rest), False)
    

    看起来很糟糕,但很有效......

    【讨论】:

      【解决方案2】:

      让我们打开警告!这可以通过-Wall 标志来完成。

      $ ghci -Wall
      > :{
      | splitSen :: String -> [(String,Int)]
      | splitSen cs = foldr func [] cs where
      |   func ' ' ((c1,n1) : ps) = ps
      |   func c ((c1,n1) : ps) = (c:c1,1+n1):ps
      | :}
      
      <interactive>:6:3: warning: [-Wincomplete-patterns]
          Pattern match(es) are non-exhaustive
          In an equation for ‘func’:
              Patterns not matched:
                  p [] where p is not one of {' '}
                  ' ' []
      
      <interactive>:6:14: warning: [-Wunused-matches]
          Defined but not used: ‘c1’
      
      <interactive>:6:17: warning: [-Wunused-matches]
          Defined but not used: ‘n1’
      

      在上面,警告告诉[] 没有在func 中处理空列表案例。

      【讨论】:

      • 确实如此,但我现在也发现我的整个函数都不正确。
      • @BohdanChornopolskyi 我没有考虑太多如何解决它,但是您可能需要使用移动复杂的“累​​加器”而不仅仅是最终结果列表。也许你需要一对包含 1)你的列表和 2)一个布尔值,指示下一个非空格是否开始它自己的单词,以便以某种方式跟踪空格。在foldr 之后,您可以用fst 丢弃布尔值。此技术与您上一个问题中使用的技术相同:构建一个包含更多折叠信息的元组,并在最后丢弃一半。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      相关资源
      最近更新 更多