[Haskell-cafe] how can this code be less?

Dan Weston westondan at imageworks.com
Thu Apr 24 22:40:23 EDT 2008


cetin tozkoparan wrote:
> I wrote this code and Can it be less?
> [2,4,5] list is sub list of [3,7,*2,4,5*,9] list and return True but 
> not of [3,7,*4,2,5*,9] list ; return False
> 
> sublist :: Eq a => [a] -> [a] -> Bool
> sublist [] _     = True
> sublist (_:_) []   = False
> sublist (x:xs) (y:ys)
>   | x == y      =  if isEqual (x:xs) (y:ys) == False
>                         then sublist (x:xs) ys
>                         else True
>   | otherwise   = sublist (x:xs) ys 
> 
> 
> isEqual :: Eq a => [a] -> [a] -> Bool
> isEqual [] _     = True
> isEqual (_:_) [] = False
> isEqual (x:xs) (y:ys)
>   | x==y    = isEqual xs ys
>   | otherwise    = False

One way is to use existing library functions as Henning suggested (but 
maybe you missed it because he mischievously changed the subject!)

Henning Thielemann wrote:
 > try 'List.tails' and 'List.isPrefixOf'

You should be able to define sublist using only some combination of the 
following (and one pair of parentheses) in one line of code!

import List(isPrefixOf,tails)

(.)        :: (b -> c) -> (a -> b) -> a -> c
any        :: (a -> Bool) -> [a] -> Bool
tails      :: [a] -> [[a]]
isPrefixOf :: (Eq a) => [a] -> [a] -> Bool


More information about the Haskell-Cafe mailing list