问题
My professor gave me an example to get last element in the list using "laste
" function:
he stated that: definition in the form of “laste xs = …
” is not acceptable, whereas definition in the form of “laste = …
” is acceptable.
I have tried something like this: Please correct me if my solution is wrong according to problem statement.
laste :: [a] -> Maybe a
laste [] = Nothing
laste (x:[]) = Just x
laste (x:xs) = laste xs
But this gives me answer for example:
ghci>laste[1,2,3,4]
Just 4
I want to get rid of this "Just
".
Is there any solution to remove Just
?
回答1:
You would need to change the signature of the function to return a simple element.
The thing is that you would need to return an error in case of empty list.
laste :: [a] -> a
laste [] = error "Can't handle empty lists." -- or some other error message
laste [x] = x
laste (x:xs) = laste xs
回答2:
While Charmini2's answer is functionally correct, it doesn't solve the problem of retrieving the last element in pointfree form. Consider
laste :: [a] -> a
laste = foldr1 (\_ a -> a)
It works according to specs as foldr1 expects a non-empty list. Intuition for why it returns the last element in the list can be gotten from the observation that foldr1 replaces every (:) in the structure of the list with the lambda in the above equation, which basically selects the rightmost of two elements. Repeat, and you get the last.
回答3:
I think your professor meant was that you need to re-implement the Prelude function last in a point-free style.
non point-free example:
filterEven xs = filter even xs
point-free exapmle:
filterEven = filter even
point-free examples of last:
lastv1 = (head . reverse)
lastv2 = foldl1 (\acc x -> x)
lastv3 = foldr1 (\x acc -> acc)
lastv4 = \(x:xs) -> if null xs then x else lastv4 xs
lastv5 = \e -> case e of
[x] -> x
(_:xs) -> lastv5 xs
otherwise -> error "empty list"
回答4:
Here a possible working solution:
last' :: [a] -> a
last' [] = error "empty"
last' (x:[]) = x
last' (x:xs) = last' xs
来源:https://stackoverflow.com/questions/19746639/how-to-return-last-element-in-the-list-using-function-in-haskell