Struggling to learn Haskell, how does one take the head of a string and compare it with the next character untill it finds a character thats note true?
In pseudo code I’m trying to:
while x == ‘next char in string’ put in new list to be returned
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The general approach would be to create a function that recursively evaluates the head of the string until it finds the false value or reaches the end.
To do that, you would need to
I have notes on Haskell that you may find useful, but you may well find Yet Another Haskell Tutorial more comprehensive (Sections 3.3 Lists; 3.5 Functions; and 7.8 More Lists would probably be good places to start in order to address the bullet points I mention)
EDIT0:
An example using guards to test the head element and continue only if it the same as the second element:
EDIT1:
Here is a concrete example to, hopefully, highlight the different between the if,then, else concept the quote suggests and what is happening in the
SomeFunfunction:When we call
SomeFun [a,a,b,b]we match this toSomeFun [x:y:xs]and sincexis ‘a’, andyis ‘a’, andx==y, thenSomeFun [a,a,b,b] = SomeFun [a,b,b], which again matchesSomeFun [x:y:xs]but conditionx==yis false, so we use the otherwise guard, and so we getSomeFun [a,a,b,b] = SomeFun [a,b,b] = []. Hence, the result ofSomeFun [a,a,b,b]is[].So where did the data go? .Well, I’ll hold my hands up and admit a bug in the code, which is now a feature I’m using to explain how Haskell functions work.
I find it helpful to think more in terms of constructing mathematical expressions rather than programming operations. So, the expression on the right of the
=is your result, and not an assignment in the imperative (e.g. Java or C sense).I hope the concrete example has shown that Haskell evaluates expressions using substitution, so if you don’t want something in your result, then don’t include it in that expression. Conversely, if you do want something in the result, then put it in the expression.
Since your psuedo code is
I’ll modify the SomeFun function to do the opposite and let you figure out how it needs to be modified to work as you desire.
Example Output:
SomeFun2 [a,a,b,b] = []SomeFun2 [a,b,b,a,b] = [a]SomeFun2 [a,b,a,b,b,a,b] = [a,b,a]SomeFun2 [a,b,a,b] = [a,b,a,b](I’d like to add at this point, that these various code snippets aren’t tested as I don’t have a compiler to hand, so please point out any errors so I can fix them, thanks)