英文:
trying to implement tail function in haskell?
问题
作为学习 Haskell 的一部分,我正在尝试实现与列表相关的各种函数的自己版本,这是我目前关于 tail
函数的实现:
tail' :: [a] -> [a]
tail' [a] = []
tail' (_:y:xs) = y:tail' xs
我正在学习 Haskell。
英文:
as a part of learning Haskell, i'm trying to implement my own version of various functions related to list, here my impleentation of tail function so far
tail' :: [a] -> [a]
tail' [a] = []
tail' (_:y:xs) = y:tail' xs
i'm learning haskell
答案1
得分: 2
你的 tail'
会递归并省略第一、第三、第五等元素。确实:
tail' [1,4,2,5]
-> 4 : tail' [2,5]
-> 4 : 5 : tail' []
tail
不需要递归(也不是尾递归 ),你可以直接解包列表的 "cons" 并返回尾部,所以:
tail' :: [a] -> [a]
tail' (_:xs) = xs
对于空列表,没有结果,使 tail'
成为一个非全函数,在 Haskell 中通常不是一个好主意。通常使用 Maybe
来模拟非全函数,其中在没有结果的情况下返回 Nothing
,所以:
tail' :: [a] -> Maybe [a]
tail' [] = Nothing
tail' (_:xs) = Just xs
英文:
Your tail'
recurses and will leave out the first, third, fifth, etc. elements. Indeed:
tail' [1,4,2,5]
-> 4 : tail' [2,5]
-> 4 : 5 : tail' []
tail does not need any recursion (nor tail recursion ), you can just unpack the "cons" of the list, and return the tail, so:
tail' :: [a] -> [a]
tail' (_:xs) = xs
for the empty list, there is no result, making tail'
a non-total function, which is often not a good idea in Haskell. Often a Maybe
is used to simulate non-total function, where we return Nothing
in case there is no result, so:
tail' :: [a] -> Maybe [a]
tail' [] = Nothing
tail' (_:xs) = Just xs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论