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

Ketil Malde ketil at malde.org
Fri Apr 25 02:51:00 EDT 2008

```cetin tozkoparan <cetintozkoparan at yahoo.com> writes:

> sublist :: Eq a => [a] -> [a] -> Bool
> sublist [] _     = True
> sublist (_:_) []   = False

This can be simplified a bit, I think (Reformatted to one line):

> sublist (x:xs) (y:ys)
>   | x == y = if isEqual (x:xs) (y:ys) == False then sublist (x:xs) ys else True

I don't like the "== False" for boolean expressions, so I'd write:

sublist (x:xs) (y:ys)
| x == y = if not (isEqual (x:xs) (y:ys)) then sublist (x:xs) ys else True

Or, swithing then and else clauses:

sublist (x:xs) (y:ys)
| x == y = if isEqual (x:xs) (y:ys) then True else sublist (x:xs) ys

If you look at the following clause:

>   | otherwise   = sublist (x:xs) ys

you'll notice that it is the same as the "else" clause.  We can
therefore write:

sublist (x:xs) (y:ys)
| x == y && isEqual (x:xs) (y:ys) = True
| otherwise = sublist (x:xs) ys

isEqual will re-test x==y, so this is redundant:

sublist (x:xs) (y:ys)
| isEqual (x:xs) (y:ys) = True
| otherwise = sublist (x:xs) ys

The pattern guard is a bit gratuitious, why not write:

sublist (x:xs) (y:ys) = isEqual (x:xs) (y:ys) || sublist (x:xs) ys

Which is how you'd define the problem: a list xs is a sublist of ys if they
have equal prefixes, or if xs is a sublist of the tail of ys.

> isEqual :: Eq a => [a] -> [a] -> Bool

Slightly misleading name, since it checks a prefix, not complete equality.

> isEqual [] _     = True
> isEqual (_:_) [] = False
> isEqual (x:xs) (y:ys)
>   | x==y    = isEqual xs ys
>   | otherwise    = False

Similar to the above, you could write:

isEqual (x:xs) (y:ys) = x == y && isEqual xs ys

"lists (x:xs) and (y:ys) 'isEqual' if x == y and xs 'isEqual' ys"

As pointed out, you could (and should) write this using a couple of
Prelude functions.  Oh, any errors in the code are left as excercises
for the reader (in other words, I didn't test this code at all, but
don't want to be perceived as lazy.)

-k
--
If I haven't seen further, it is by standing in the footprints of giants
```