level 2
478934853
楼主
写一个程序,输入一个元素和list。返回这个元素之前的一个元素。
举例说明:
elementBefore 3 [1,2,3,4,5] should return Just 2
elementBefore ’h’ "elephant" should return Just 'p'
elementBefore ’z’ "elephant" should return Nothing
elementBefore ’e’ "elephant" should return Nothing
自己写了一个。。可以运行但是感觉好蠢。。。求更好的。。。
elementPosition :: (Eq t) => t -> [t] -> Int
elementPosition elt (x:xs) = if elt/= x then 1 + elementPosition elt xs
else 0
elementPosition elt [] = error "Couldn't find the value in the list"
elementBefore :: Eq a => a -> [a] -> Maybe a
elementBefore elt xs
| ((elementPosition elt xs)-1) == (-1) = Nothing
| (elt `elem` xs) == True = Just (xs!!((elementPosition elt xs)-1))
| otherwise = Nothing
2016年08月15日 05点08分
1
举例说明:
elementBefore 3 [1,2,3,4,5] should return Just 2
elementBefore ’h’ "elephant" should return Just 'p'
elementBefore ’z’ "elephant" should return Nothing
elementBefore ’e’ "elephant" should return Nothing
自己写了一个。。可以运行但是感觉好蠢。。。求更好的。。。
elementPosition :: (Eq t) => t -> [t] -> Int
elementPosition elt (x:xs) = if elt/= x then 1 + elementPosition elt xs
else 0
elementPosition elt [] = error "Couldn't find the value in the list"
elementBefore :: Eq a => a -> [a] -> Maybe a
elementBefore elt xs
| ((elementPosition elt xs)-1) == (-1) = Nothing
| (elt `elem` xs) == True = Just (xs!!((elementPosition elt xs)-1))
| otherwise = Nothing
