Recursion over lists in Haskell -


For example, I have a list as ['a', 'b', 'c', 'd', '',

I want to do something like this: first, do something with the first two elements, f 'a' 'b'. Then do the same with the return value of the next and the element in the list, result = f 'A' says 'B', like F results 'C' then F result (result 'C') 'D' and so on.
How can I do something like this?

First let us consider that function f that you have it stored The value takes some kind of a simple value, and consequently combines them. Therefore, in type signature, we will call a for the type of stored value, type of value v , and r the type of result for.

  f :: a - & gt; V - & gt; R   

Now we want to create a folding function which uses the f and the list of values.

  someFold :: (A -> - v - & gt; r) - & gt; [V] - & gt; ?   

What should it return? It should produce some of the resulting type r , right? Now note that a and r must actually be of the same type, because we will continue repeating the result of f for the first time .

  someFold :: (a -> v - & gt; a) - & gt; [V] - & gt; One   

Now one thing is missing How do you get the first a ? There are two ways to consider that, either you select the first value, in that case a is the same as v , or you specify a base value , Therefore, a is actually different from v . Let's go with the latter, because it is even more interesting to decide from left to right in this list. (This is what you want, right?)

  some fold :: (a -> v -> a) -> A - & gt; [V] - & gt; A   

So ... how do we implement it? It will be recursive, so we start with base cases.

  some folds FAC [] = ACC   

If we are at the end of the list, then we have deposited enough, right? He was so easy So how about the recursive case? On each step you said, we should apply "code so far" to "accumulated value" so the first code in each step, and the second "first value of the list". f ACC X . Then we put the fold in the form of our new "accumulated" value using that .

  some fold FA (x: xs) = someFold f (f acc x) xs   

Easy, right? But ... what if we want you to do this and start work on the first two values ​​of the list? Also easy to take just the first element, and call it the original "base" cache!

  someFold1 :: (v -> v -> v) - & gt; [V] - & gt; V someFold1f (x: xs) = someFold fx xs   

Note that because a is the case as v for this special There is a very interesting type of signature in Function someFold1 . If you understand this explanation, then congratulations. We have just implemented

  Prelude & gt; "ABCDE" literally ['A', 'B', 'C', 'D', 'E'] 'A' [/ code]  

Code, you really should use it and friends .

Comments