Sunday, 5 June 2016

Haskell: Implement deleteBy function

The 'deleteBy' function behaves like 'delete', instead of deleting the first occurrence of element, it deletes the element based on given predicate function.

For Example, as per following function, two numbers are equal if their remainders are equal.

check a b = ((a `mod` 10) == (b `mod` 10))

When you execute the following statement,
deleteBy check 20 [2, 3, 5, 100, 123, 400]


It compares the elements based on ‘check’ function. As per this function 20, 100, 400 are equal, since their remainders are zero, when divided by 10.  It removes 100 from the list.
*Main> :m Data.List
Prelude Data.List> 
Prelude Data.List> :t deleteBy
deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
Prelude Data.List> 
Prelude Data.List> let check a b = ((a `mod` 10) == (b `mod` 10))
Prelude Data.List> 
Prelude Data.List> deleteBy check 20 [2, 3, 5, 100, 123, 400]
[2,3,5,123,400]
Prelude Data.List> 
Prelude Data.List> deleteBy check 23 [2, 3, 5, 100, 123, 400]
[2,5,100,123,400]


ListUtil.hs
deleteByPredicate :: (a->a->Bool) -> a -> [a] -> [a]
deleteByPredicate fun ele [] = []
deleteByPredicate fun ele (x:xs)
    | (ele `fun` x) = xs
    | otherwise = x : deleteByPredicate fun ele xs

*Main> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> :t deleteByPredicate
deleteByPredicate :: (a -> a -> Bool) -> a -> [a] -> [a]
*Main> 
*Main> let check a b = ((a `mod` 10) == (b `mod` 10))
*Main> 
*Main> deleteByPredicate check 20 [2, 3, 5, 100, 123, 400]
[2,3,5,123,400]
*Main> 
*Main> deleteByPredicate check 23 [2, 3, 5, 100, 123, 400]
[2,5,100,123,400]
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment