无法理解元组递归在Haskell中是如何工作的

Sil*_*Way 6 recursion haskell tuples list

我无法理解这个功能是如何工作的.该函数应该接受一个字符串并将该字符串拆分成一对,其中第一个元素是字符串中的第一个"字",第二个元素是输入字符串的其余部分.

特别是,在第6行,我理解为什么函数应当在isSpace c为true 时终止但不理解为什么它应该返回第一个元素为空列表的元组.我想知道是否有人可以解释为什么这适用于一个相对简单(但非平凡)的例子,如nextWord "an apple".

import Data.Char
nextWord :: String -> (String, String)
nextWord []
  = ([],[])
nextWord (c:cs)
  | isSpace c = ([], cs)
  | otherwise = (c: word, other)
  where
    (word, other) = nextWord cs
Run Code Online (Sandbox Code Playgroud)

编辑:作为给定参数以空格开头时此函数返回的示例,nextWord"hello"应返回("","hello").

ram*_*ion 7

让我们一步一步吧!

nextWord "an apple"
Run Code Online (Sandbox Code Playgroud)

由于"an apple"没有模式匹配[],我们在第二种情况.代入'a': "n apple"c : cs,我们得到:

nextWord ('a':"n apple")
  | isSpace 'a' = ([], "n apple")
  | otherwise = ('a': word, other)
  where
    (word, other) = nextWord "n apple"
Run Code Online (Sandbox Code Playgroud)

isSpace 'a'是的False,所以这简化为

nextWord ('a':"n apple") = ('a': word, other)
  where (word, other) = nextWord "n apple"
Run Code Online (Sandbox Code Playgroud)

同样,nextWord "n apple"我们得到了

nextWord ('n':" apple") = ('n': word, other)
  where (word, other) = nextWord " apple"
Run Code Online (Sandbox Code Playgroud)

而且nextWord " apple"我们得到了

nextWord (' ':"apple")
  | isSpace ' ' = ([], "apple")
  | otherwise = ('a': word, other)
  where
    (word, other) = nextWord "n apple"
Run Code Online (Sandbox Code Playgroud)

这简化为

nextWord (' ':"apple") = ([], "apple")
Run Code Online (Sandbox Code Playgroud)

换回我们的表达式nextWord "n apple",我们得到

nextWord ('n':" apple") = ('n': word, other)
  where (word, other) = ([], "apple")
Run Code Online (Sandbox Code Playgroud)

这简化为

nextWord ('n':" apple") = ('n':[], "apple")
Run Code Online (Sandbox Code Playgroud)

要么

nextWord ('n':" apple") = ("n", "apple")
Run Code Online (Sandbox Code Playgroud)

现在把它替换回我们的表达式中nextWord "an apple",我们得到了

nextWord ('a':"n apple") = ('a': word, other)
  where (word, other) = ("n", "apple")
Run Code Online (Sandbox Code Playgroud)

这简化为

nextWord ('a':"n apple") = ('a':"n", "apple")
Run Code Online (Sandbox Code Playgroud)

要么

nextWord ('a':"n apple") = ("an", "apple")
Run Code Online (Sandbox Code Playgroud)