我想在haskell中创建一个函数,它给我x位置的项目。
例如:
[1..10] `give` 3 => should give me 4
在java中这没问题,但是如何在Haskell中处理呢
give :: [b] -> Integer -> Maybe b
give ????
答案 0 :(得分:2)
我倾向于尽可能避免显式递归。函数组合产生更易读的代码,并且组成标准库函数导致可靠的代码。所以这是我的版本:
import Data.Maybe
give :: [a] -> Integer -> Maybe a
give xs n = listToMaybe $ drop n xs
说明:drop n xs
删除了第一个n
元素,因此drop 3 [1..5]
会返回[4,5]
。 listToMaybe
返回Nothing
表示空列表,Just x
表示(x:_)
。
答案 1 :(得分:1)
试试这个,它对我有用。
give :: [b] -> Integer -> Maybe b
give [] _ = Nothing
give (x:xs) 0 = Just x
give (x:xs) index = give xs (index - 1)
答案 2 :(得分:0)
除上述内容外,还有另一个有趣的解决方案:
give xs n = head $ iterate tail xs !! n