所以今天早些时候我问过通过foldr实现inits.我现在有类似的尾巴问题.首先要做的是:我有一个解决方案.然而,这不是我需要的解决方案,而是我应得的解决方案.或类似的东西:
码:
tails :: [a] -> [[a]]
tails = foldr ( \ x y -> reverse([] : reverse(map (x:) y) )) [[]]
Run Code Online (Sandbox Code Playgroud)
这提供了正确的结果,但它不符合我们的教授为我们设定的模式.模式看起来像这样:
tails :: [a] -> [[a]]
tails = foldr ( \ x y -> undefined : undefined ) undefined
Run Code Online (Sandbox Code Playgroud)
所以显然我的功能需要调整,但是我不会理解它,因为我总是回到我的解决方案.
如何更好地解决这个问题的任何提示?
提前致谢.
解决了:
tails :: [a] -> [[a]]
tails = foldr ( \ x y -> (x : (head y)) : y) [[]]
Run Code Online (Sandbox Code Playgroud)
一些提示:
你知道这一点tails [] == [[]]
,所以你的初始值必须是[[]]
,所以你会有
tails = foldr (\x y -> undefined : undefined) [[]]
length (tails xs !! n) > length (tails xs !! (n+1))
,或者用简单的英语来说:随着您沿着列表向下移动,每条尾巴的长度都会变短。
你有什么想法foldr (\x (y:ys) -> undefined : undefined) [[]]
?
如果你在一段时间后再次陷入困境(或者已经想到了这些),请发表评论,我会再次推动你。