N
N
Nikitos_STR2016-11-14 01:06:30
Haskell
Nikitos_STR, 2016-11-14 01:06:30

How to determine if a list is a sublist?

Hello, I have a task: There are two lists. Determine if the first list is a sublist of the second.
I wrote the code, it looks like it should work, but it doesn't. Can anyone suggest what I did wrong?
Thank you.

sublist v w = 
  if w == [] 
    then False
    else if v == h_w 
      then True
      else if h_w /= [] 
        then sublist v h_w
        else sublist v t_w
  where 
    h_w = head w
    t_w = tail w

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Moseychuk, 2016-11-14
@Nikitos_STR

  1. Use pattern matching in function definition instead of footcloth if/else
    And now for the algorithm. It is more imperative than functional.
    If you do not need to build a data structure (for example, fill in a tree) during the execution of the algorithm, then often recursion can be abandoned.
    isSublist :: Eq a => [a] -> [a] -> Bool
    isSublist a b = all (`elem` b) a

    If elem cannot be used, then you can define this function yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question