【问题标题】:Split list of characters into list of words将字符列表拆分为单词列表
【发布时间】:2018-03-13 09:43:27
【问题描述】:

我目前正在学习 SML 函数式语言,我正在尝试创建一个函数,该函数接受一个字符列表,然后它在找到一个空格时搜索列表中的任何空格,它将空格前的字符连接起来一个字符串,然后它返回一个由空格分隔的字符组成的字符串列表。

这是我的代码,但是编译器说 eof 有错误!

fun sepWords ([]) = []
  | sepWords (x :: xs) =
    let 
      val word = "" 
      val list
      sepWords (xs)
    in 
      if (Char.isSpace (x)) then (word = "")
      else (word ^ x)
      word :: list
    end;

【问题讨论】:

    标签: string list function sml chars


    【解决方案1】:
    1. val listsepWords (xs) 行周围存在语法错误。也许您打算写val list = sepWords (xs)?在if ...word :: list 行周围也有语法错误。我不确定这里的意图是什么,但也许您认为word :: list 会产生将“单词”添加到“列表”的副作用?

    2. if ... 中有类型错误,因为“then”分支的表达式 word = "" 的类型为 bool,而“else”分支的表达式为 @987654329 @ 类型为 string。 if-then-else 在每个分支上必须具有相同的类型,类型检查器才能接受程序。

    3. 与其创建一个类型为 char list -> string list 的函数,为什么不创建一个类型为 string -> string list 的函数呢?如果这样做,您甚至可以通过跟踪原始字符串中的字符索引(例如,使用 substring 类型)。

      该函数的一个好名字可能是“单词”。

    4. 当多个空格连续出现时,您尚未定义行为。 words "hello world" 应该产生["hello", "world"] 还是["hello", "", "world"]

    5. 实际上有内置的库函数可以做到这一点:

      - String.tokens Char.isSpace "hello  world";
      > val it = ["hello", "world"] : string list
      
      - String.fields Char.isSpace "hello  world";
      > val it = ["hello", "", "world"] : string list
      
    6. 首先将您的 string 转换为 char 列表 的替代方法是列表递归的一个很好的练习,即使该策略不是很有效。您可以通过解决从输入中提取单个单词以及字符串其余部分的问题来解决此问题:

      fun firstWord [] = ([], [])
        | firstWord (c::cs) =
          if Char.isSpace c
          then ([], cs)  (* throw away the space c *)
          else case firstWord cs of
                 (fw, remainder) => (c::fw, remainder)
      

      你可以这样称呼:

      - firstWord (explode "hello  world");
      > val it =
          ([#"h", #"e", #"l", #"l", #"o"], [#" ", #"w", #"o", #"r", #"l", #"d"])
              : char list * char list
      

      只要余数不为空,就可以递归调用:

      fun words [] = []
        | words cs =
          let val (fw, remainder) = firstWord cs
          in implode fw :: words remainder end
      

      然后使用这个:

      - allWords (explode "hello  world");
      > val it = ["hello", "", "world"] : string list
      

    【讨论】:

    • 非常感谢。你的回答不仅解决了我的问题,还教会了我很多我不知道的事情。你是最棒的!
    猜你喜欢
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2023-01-22
    • 2017-08-16
    • 1970-01-01
    • 2018-06-15
    • 2021-05-26
    • 1970-01-01
    相关资源
    最近更新 更多