Haskell - Filter Last Element

后端 未结 4 1450
北荒
北荒 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:06

    The minimal change that will cause filterLast to compile is to use (++) instead of (:), as in:

    filterLast p xs 
        | p (last xs) = filterLast p (init xs) ++ [last xs]
    

    (Other lines remain the same.) The (:) function is specifically for putting a single extra element at the beginning of a list, which is not what you wanted to do here. For smallerOne, you may simply change the type signature in the way suggested by the error message, thus:

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

提交回复
热议问题