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

时间:2014-12-27 18:54:26

标签: list haskell recursion tuples

我无法理解此功能的工作原理。该函数应该接受一个字符串并将该字符串拆分成一对,其中第一个元素是第一个单词'在字符串中,第二个元素是输入字符串的其余部分。

特别是,在第6行,我理解为什么函数应该在isSpace c为真时终止但不理解为什么它应该返回第一个元素为空列表的元组。我想知道是否有人可以解释为什么这适用于一个相对简单(但非平凡)的例子,如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

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

1 个答案:

答案 0 :(得分:7)

让我们一步一步!

nextWord "an apple"

由于"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"

isSpace 'a'False,因此简化为

nextWord ('a':"n apple") = ('a': word, other)
  where (word, other) = nextWord "n apple"

同样,对于nextWord "n apple"我们得到

nextWord ('n':" apple") = ('n': word, other)
  where (word, other) = nextWord " apple"

nextWord " apple"我们得到

nextWord (' ':"apple")
  | isSpace ' ' = ([], "apple")
  | otherwise = ('a': word, other)
  where
    (word, other) = nextWord "n apple"

简化为

nextWord (' ':"apple") = ([], "apple")

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

nextWord ('n':" apple") = ('n': word, other)
  where (word, other) = ([], "apple")

简化为

nextWord ('n':" apple") = ('n':[], "apple")

nextWord ('n':" apple") = ("n", "apple")

现在将其替换回nextWord "an apple"的表达式,我们得到

nextWord ('a':"n apple") = ('a': word, other)
  where (word, other) = ("n", "apple")

简化为

nextWord ('a':"n apple") = ('a':"n", "apple")

nextWord ('a':"n apple") = ("an", "apple")