“尝试在Haskell中实现tail函数?”

huangapple go评论50阅读模式
英文:

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 不需要递归(也不是尾递归 “尝试在Haskell中实现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 “尝试在Haskell中实现tail函数?” ), 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

huangapple
  • 本文由 发表于 2023年5月15日 06:21:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定