如何使用Haskell中的函数返回列表中的最后一个元素? [英] How to return last element in the list using function in haskell?
问题描述
我的教授给了我一个使用" laste
"函数获取列表中最后一个元素的示例:他说:以" laste xs =…
"的形式进行定义是不可接受的,而以" laste =…
"的形式进行定义是可以接受的.
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
我想摆脱这个" Just
".
有什么解决方法可以删除 Just
?
Is there any solution to remove Just
?
推荐答案
虽然Charmini2的回答在功能上是正确的,但它不能解决以无点形式检索最后一个元素的问题.考虑
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)
它按照规范工作,因为foldr1需要一个非空列表.可以从以下观察得出直觉,为什么它返回列表中的最后一个元素:观察到的是foldr1用上述等式中的lambda替换了列表结构中的每个(:),基本上选择了两个元素中最右边的一个.重复,您将得到最后一个.
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.
这篇关于如何使用Haskell中的函数返回列表中的最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!