[英]Haskell tail function for empty lists
I have a problem with a function that should only return the tail of a list. 我有一个函数的问题,该函数应该只返回列表的尾部。 The functions is myTail and should give a useable result, even if the input is an empty list.
函数是myTail,即使输入是空列表,也应该给出一个可用的结果。
I want to understand all 3 ways: pattern matching, guarded equation and conditional expressions 我想了解所有3种方式:模式匹配,保护方程和条件表达式
this works: 这工作:
> myTail_pat :: [a] -> [a]
> myTail_pat (x:xs) = xs
> myTail_pat [] = []
But this: 但是这个:
> myTail_guard (x:xs) | null xs = []
> | otherwise = xs
gives me the error: Program error: pattern match failure: myTail_guard [] How can i declare the function without patterns? 给我错误:程序错误:模式匹配失败:myTail_guard []如何声明没有模式的函数?
Thank you. 谢谢。
The pattern x:xs
does not match the empty list. 模式
x:xs
与空列表不匹配。 You'd need to do: 你需要这样做:
myTail_guard xs
| null xs = []
| otherwise = tail xs
drop 1 is safe 丢弃1是安全的
drop 1 []
-- result: []
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.