
Stefan Höck schreef op 10-11-2014 17:18:
I try to say that if the input list has only 1 item the outcome is the head of that list. This is not how one typically thinks about folds. Look at the type of acc:
acc :: a -> Maybe a -> Maybe a
acc is a function wich takes two arguments (ignoring currying): On is of type `a`. This is the element type of the list you fold over. The other is of type `Maybe a`. This is the value you accumulate in your fold. The initial value is `Nothing`. You start your fold literally with nothing, since you haven't visited any element in the list yet. Now the first element of the list (see below) is passed to acc. What do you do with it?
acc a Nothing = ???
a is an element in your lit, Nothing is the value you have accumulated so far. What do you do? Ignore a? Keep it? If you ignore a, you return `Nothing`.
acc a Nothing = Nothing
With this accumulator, the list will be traversed (ignoring lazy evaluation for the time being), all values will be ignored and your result will be Nothing, no matter what kind of list you fold over. Therefore, let's keep value `a`. In order to do that, we have to wrap it in a Just, otherwise the types won't match:
acc a Nothing = Just a
This function will give the right result for empty lists (Nothing) and for lists with a single value where the value is wrapped in a Just. The function will throw an error however, if you pass it a list containing more than one element, because the pattern match is not exhaustive. We need to decide what happens, when we already have a value wrapped in a Just:
acc a Just b = ???
It makes sence except when I enter acc a Just B I see this error message : ConstructorJustshould have 1 argument, but has been given none…