First consider the following code, which counts the number of blank spaces in a string:
countSpaces :: String -> Int
countSpaces [] = 0
countSpaces (c : restOfString)
= d + countSpaces restOfString
where d = if c == ’ ’ then 1
else 0
Here is my questions:
1, if I make a call: countSpaces "abc" , then what happens when this function tries to match the string "abc" with (c: restOfString). I mean, restOfString is: "abc" in this call but what is (c:restOfString) ? you are 'consing' something(the variable? c ) to restOfstring and then you are trying to match? I just don't get it.
2, I try to run the code but I am getting a parse error why?
parse error on input ‘´’
3,will this function call countSpaces to infinity? since restOfString is always the same and not reduced, eg. making the call countSpaces "aaa" will not change after the first call,second or any call, right?
- Added afterwards*
Now consider this code which completes the same task:
countSpaces :: String -> Int
countSpaces [] = 0
countSpaces (’ ’ : restOfString)
= 1 + countSpaces restOfString
countSpaces (_ : restOfString)
= 0 + countSpaces restOfString
1, so if we try to make a call countSpaces "abc" the pattern (’ ’ : restOfString) will just get bigger since every time countSpaces gets called this will just cons a ' ' to restOfString, Unless every time countSpaces will get called the first char in the string will be changed to: ' ' . so in the first call of countSpaces "abc" then (’ ’ : restOfString) is ' ':"bc" , which is confusing right, since it replaced "a" with a blank instead of consing it so that we get: " abc"
"abc"is just syntactic sugar for['a', 'b', 'c']or'a':'b':'c':[].'to yours,’. They're different characters.