【问题标题】:Trouble understanding how tuple recursion works in Haskell无法理解 Haskell 中的元组递归是如何工作的
【发布时间】:2015-02-24 13:17:10
【问题描述】:

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

特别是在第 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 "hello" 应返回 ("", "hello")。

【问题讨论】:

  • “为什么应该返回一个元组,第一个元素是空列表”。它应该返回什么?
  • 你能在 Haskell 中写下这个值吗?
  • 这不是元组递归。它是一个返回元组的递归函数。在空格情况下,它返回空列表作为第一个组件:这实际上是空字符串。这样做是为了递归调用可以在前面添加字符,从而隔离输入字符串中的第一个单词。
  • @Jubobs 我解释了这个问题。这只是练习 Haskell 的整个 pdf 函数中的一个函数。然而,规范没有提到论点从空格开始的情况,所以它是模棱两可的。但是,在找到解决方案并使用该函数后,它似乎“忽略”了这种情况,因此 nextWord "hello" 返回 ("", "hello")。我的问题是,我不明白终止案例(第 6 行)如何逐个字符地构建单词并在它似乎返回一个元组时返回正确的元组,其中第一个元素是 [],第二个元素是 cs。

标签: list haskell recursion tuples


【解决方案1】:

让我们一步一步来!

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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    相关资源
    最近更新 更多