2014-12-27 68 views
6

我很难理解这个函数是如何工作的。该函数应该接受一个字符串并将该字符串拆分为一对,其中第一个元素是字符串中的第一个“单词”,第二个元素是输入字符串的剩余部分。理解哈斯克尔元组递归的工作原理

特别是,在第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

“为什么要返回一个元组与第一元素是空的列表“。它应该返回什么呢? – 2014-12-27 19:04:08

+0

你可以在Haskell中写下该值吗? – 2014-12-27 19:05:03

+0

这不是元组递归。它是一个返回元组的递归函数。在空格中,它返回空列表作为第一个组件:这实际上是空字符串。这样做是为了使递归调用可以添加前面的字符,以隔离输入字符串中的第一个字。 – chi 2014-12-27 21:28:09

回答

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