返回列表中指定位置的项目

时间:2018-02-17 02:09:05

标签: haskell recursion

我正在尝试使用递归函数在列表中的特定位置找到en元素。该函数有2个参数,一个int&名单。 int是列表中项目的位置。我指定了2个案例,第一个案例为空列表提供,第二个案例为非空列表。

.hs代码

findKthElem :: Ord a => Int -> [a] -> a
findKthElem x [] = error "empty list provided"
findKthElem x (y:ys) = if x==1 then y else findKthElem (x-1) ys  

输入

*Main> findKthElem 0 [1..99]

输出

** Exception: empty list provided

预期输出

 1

因为我是Haskell的新手,所以我无法理解我哪里出错了。请帮助。

1 个答案:

答案 0 :(得分:2)

使用警卫来匹配不同索引值的方法:

findKthElem :: Ord a => Int -> [a] -> a
findKthElem _ [] = error "empty list provided"
findKthElem i (x:xs) | i < 0 = error "invalid index"
                     | i == 0 = x
                     | otherwise = findKthElem (i - 1) xs

您还可以使用Maybe monad保持无错:

findKthElem :: Ord a => Int -> [a] -> Maybe a
findKthElem _ [] = Nothing
findKthElem i (x:xs) | i < 0 = Nothing
                     | i == 0 = Just x
                     | otherwise = findKthElem (i - 1) xs