Haskell - Filter Last Element

后端 未结 4 1554
北荒
北荒 2021-01-18 17:36

I want to filter the last element of a list that does not satisfy a property. An example would be

smallerOne :: a->Bool 
smallerOne x = x < 1 
         


        
4条回答
  •  天命终不由人
    2021-01-18 18:31

    smallerOne :: (Ord a, Num a) => a -> Bool 
    smallerOne x = x < 1 
    
    filterLast :: (a -> Bool) -> [a] -> [a]
    filterLast p (x:[]) = if (p x) then x:[] else []
    filterLast p (x:xs) = x : filterLast p xs
    

    This is the solution to your problem. Now, also some explanation:

    smallerOne :: (Ord a, Num a) => a -> Bool

    you must include the class constraint Ord and Num, because your are trying to ordonate numbers through this < comparison operator. You can read more here: http://learnyouahaskell.com/types-and-typeclasses#typeclasses-101

    filterLast is implemented through pattern matching, Haskell is pretty smart and will enter the branch that will match the given list, so he will enter this branch:

    filterLast p (x:[]) = if (p x) then x:[] else []

    only when there is one element left, i.e your last element.

    You said you are a beginner, I really recommend you this tutorial, http://learnyouahaskell.com/chapters, it is pretty cool.

提交回复
热议问题