For example, I have a list as ['a', 'b', 'c', 'd', '',
How can I do something like this?
First let us consider that function Now we want to create a folding function which uses the What should it return? It should produce some of the resulting type Now one thing is missing How do you get the first So ... how do we implement it? It will be recursive, so we start with base cases. 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". 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! Note that because Code, you really should use it and friends . 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
f and the list of values.
someFold :: (A -> - v - & gt; r) - & gt; [V] - & gt; ?
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
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
some folds FAC [] = ACC
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
someFold1 :: (v -> v -> v) - & gt; [V] - & gt; V someFold1f (x: xs) = someFold fx xs
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]
Comments
Post a Comment