2014-12-27 46 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")