[英]What's the proper way to write a haskell function
I'm a bit confused with an exercise. 我对运动有些困惑。 The exercice asked for a function that would take the last but one element from a list and it shows this code as the correct answer.
练习要求一个函数,该函数将使用列表中的最后一个元素,但该元素将其显示为正确答案。
myButLast :: [a] -> a
myButLast = last . init
myButLast' x = reverse x !! 1
myButLast'' [x,_] = x
myButLast'' (_:xs) = myButLast'' xs
myButLast''' (x:(_:[])) = x
myButLast''' (_:xs) = myButLast''' xs
myButLast'''' = head . tail . reverse
But I just did this and it just worked as asked 但是我只是这样做,并且按照要求工作
myButLast' = init[1,2,3,4]
myButLast'' = last myButLast'
What was all that extra code in the first solution? 第一个解决方案中所有多余的代码是什么?
The example code shows 5 different ways of implementing myButLast
. 示例代码显示了实现
myButLast
5种不同方式。 Note that myButLast
and myButLast'
are entirely different functions. 请注意,
myButLast
和myButLast'
是完全不同的功能。
About your answer - your intuition is correct, but your function only deals with one input - [1,2,3,4]
. 关于您的答案-您的直觉是正确的,但您的函数仅处理一个输入-
[1,2,3,4]
。 Instead, you can pass any list: 相反,您可以传递任何列表:
myButLast' xs = init xs
myButLast'' = last myButLast'
Combine them and add a type signature: 合并它们并添加类型签名:
myButLast :: [a] -> a
myButLast xs = last $ init $ xs
Which in pointfree style is equal to the first solution: 无点样式中的哪个等于第一个解决方案:
myButLast :: [a] -> a
myButLast = last . init
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.