使用Maybe数据类型查找列表中的数字是否在第二个列表的范围内的最佳方法是什么?
到目前为止我所拥有的:
getElems :: [Int] -> [a] -> [Maybe a]
getElems [xs] ys
| head(tail[(xs)]) > head(tail[(ys)]) = [Nothing]
| otherwise = [Just xs]
它需要返回与指定位置对应的元素。根据位置是否大于列表大小,它返回Nothing,否则只是值。
例如:
getElems [2,4] [1..10] ) [Just 3,Just 5]
getElems [2,4] [1..4] ) [Just 3,Nothing]
答案 0 :(得分:3)
您可以编写一个use
来为单个列表执行此操作:
getElementByIndex
然后只需getElementByIndex :: Int -> [a] -> Maybe a
getElementByIndex n [] = Nothing
getElementByIndex n (x:xs) = if (n == 0)
then Just x
else getElementByIndex (n - 1) xs
就可以得到答案:
map
getElems :: [Int] -> [a] -> [Maybe a]
getElems xs ys = map (\x -> getElementByIndex x ys) xs
演示:
ghci