Problem understanding how tuple recursion works in Haskell

I find it difficult to understand how this function works. It is assumed that the function takes a string and splits this string into a pair, the first element of which is the first word that is in the string, and the second is the rest of the input string.

In particular, on line 6, I understand why the function should end when isSpace c is true, but I don't understand why it should return a tuple with the first element being an empty list. I was wondering if anyone could explain why this works with a relatively simple (but non-trivial) example, for example 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 

EDIT: As an example of what this function returns when this argument starts with a space, nextWord "hello" should return ("," hello ").

+6
source share
1 answer

Let it go through it!

 nextWord "an apple" 

Since "an apple" does not match the pattern with [] , we are in the second case. Substituting in 'a': "n apple" for c : cs , we get:

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

isSpace 'a' is False , so this is simplified to

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

Similarly, for nextWord "n apple" we get

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

And for nextWord " apple" we get

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

Which makes it easier

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

Substituting back into our expression for nextWord "n apple" , we get

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

which simplifies to

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

or

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

Now, replacing this expression with our expression for nextWord "an apple" , we get

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

which simplifies to

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

or

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

Source: https://habr.com/ru/post/980212/


All Articles