Sunday 5 June 2016

Haskell: break: Divide list based on a condition

break function creates a tuple of two lists from the original one separated at condition boundary

*Main> :t break

break :: (a -> Bool) -> [a] -> ([a], [a])
*Main> break (3==) [1,2,3,4,5]
([1,2],[3,4,5])
*Main> 
*Main> break (0>=) [1,2,3,4,5]
([1,2,3,4,5],[])
*Main> 
*Main> break (4>=) [1,2,3,4,5]
([],[1,2,3,4,5])
*Main> 
*Main> break (4>=) [2, 3, 10, 12, 14, 16, 9, 8]
([],[2,3,10,12,14,16,9,8])
*Main> 
*Main> break (10==) [2, 3, 10, 12, 14, 16, 9, 8]
([2,3],[10,12,14,16,9,8])
*Main> 
*Main> break (10<=) [2, 3, 10, 12, 14, 16, 9, 8]
([2,3],[10,12,14,16,9,8])
*Main> 
*Main> break (10<) [2, 3, 10, 12, 14, 16, 9, 8]
([2,3,10],[12,14,16,9,8])
*Main> 
*Main> break ('w'==) "hello - world"
("hello - ","world")

Observe above examples; break function takes function as its first argument and a list as second argument. The function examines elements of the list and returns a Boolean value to indicate whether to break the list at that point.


Example1
*Main Data.Char> break isUpper "hello Hari How are you"
("hello ","Hari How are you")

Above snippet break the list into two sub lists, whenever it sees an upper case letter.


Example2
*Main Data.Char> break isLower "Humpty Dumpty sat on a wall"
("H","umpty Dumpty sat on a wall")


Above snippet break the list into two sub lists, whenever it sees a lower case letter.

Example 3
*Main Data.Char> break odd [2, 4, 5, 3, 2, 4, 6]
([2,4],[5,3,2,4,6])


Above snippet break the list into two sub lists, whenever it sees an odd number.

Example 4
*Main Data.Char> break even [1, 4, 5, 3, 2, 4, 6]
([1],[4,5,3,2,4,6])


Above snippet break the list into two sub lists, whenever it sees an even number.



Previous                                                 Next                                                 Home

No comments:

Post a Comment