[Haskell-beginners] Are these soloutions all valid and a good use of Haskell
Kees Bleijenberg
k.bleijenberg at lijbrandt.nl
Tue Nov 11 17:43:21 UTC 2014
Roelof,
The acc for the foldr doesn't work in foldl. But foldl is easier then foldr.
foldl traverses the list from left to right.
For foldl acc returns the current list element (second param) in a Just and
ignores the result of the partial calculation (param 1).
Walking through the list [1,2,4], acc returns for the first element Just 1,
for the second element Just 2 en finally Just 4. The result of the foldl is
in this case Just 4.
If the foldl is over the empty list, acc is never called and foldl returns
initial, so Nothing.
In code:
module Test()
where
last5 :: [a] -> Maybe a
last5 xs = foldl acc initial xs
acc :: Maybe a -> a -> Maybe a -- swapped params!
acc _ x = Just x
initial :: Maybe a
initial = Nothing
Kees
-----Oorspronkelijk bericht-----
Oke,
But what If I try it on a left folt.
Then it must be the other way.
let's say we have [1 , 2, 3]
so first it's nothing and 1 is taken.
so y could be one and nothuing must stay nothing because it's not the last
part, The same for 2 , When it's three nothing must changed to just 3.
Fold is something I find it very difficult to wrap my head around it.
Maybe haskell or any functional proggramming language is not for me,
Roelof
Kees Bleijenberg schreef op 11-11-2014 15:46:
> The program traverses the list from right to left. The first element
> that acc sees during traversal is the last element of the list.
> The idea is as follows:
> Parameter y is the partial calcresult.
> If y (in your code) is Nothing then acc returns Just x. So the new
> partial result is the current list element in a Just.
> The next time acc is called, y is not Nothing but a Just. In that case
> acc returns the partial calcresult unchanged.
> So, y is Nothing for the last list element and Just <last element of
> the
> list> for all other list elements.
>
> last5 :: [a] -> Maybe a
> last5 xs = foldr acc initial xs
>
> acc :: a -> Maybe a -> Maybe a
> acc x Nothing = Just x
> acc _ aJust = aJust
>
> initial :: Maybe a
> initial = Nothing
>
> In your code you don't need the 'where' in the acc definition. Define
> acc for Nothing and for Just.
>
> Kees
--- snip ----
More information about the Beginners
mailing list