讓我們一起穿過它!
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")
「爲什麼要返回一個元組與第一元素是空的列表「。它應該返回什麼呢? – 2014-12-27 19:04:08
你可以在Haskell中寫下該值嗎? – 2014-12-27 19:05:03
這不是元組遞歸。它是一個返回元組的遞歸函數。在空格中,它返回空列表作爲第一個組件:這實際上是空字符串。這樣做是爲了使遞歸調用可以添加前面的字符,以隔離輸入字符串中的第一個字。 – chi 2014-12-27 21:28:09