nightscream
nightscream

Reputation: 23

Look up or insert new element to string list in Haskell

So I want to have a function that takes a String and a list as an argument, and checks if that element is already on the list, if it is, returns the same list, if it isnt, adds it to the list and returns it, 'im a begginer with haskell so heres what I have tried with no sucess:

check:: String ->[String] ->[String]
check x [] = []++[x]
check x (y:xs) 
             | x==y = (y:xs)
             | otherwise = check x xs 

Can someone point me the way ? thks

Upvotes: 0

Views: 1090

Answers (2)

Lee Duhem
Lee Duhem

Reputation: 15121

To implement check, we need to compare the elements of its second argument, l, one by one with its first argument, x. These elements of l that do not equal to x should be elements of the final result. If we find an element of l that equals x, there is no need to compare the rest of l with x.

So check can be implemented by using recursion like this

check x [] = [x]
check x l@(y:ys)
    | x == y    = l -- `l` is `y:ys`
    | otherwise = y : check x ys

Explanation:

  1. If the second argument is empty list, then the result is [x];

  2. otherwise if the head of the second argument equals its first argument, the result should be the second argument;

  3. finally, the head of its second argument should be part of the final result, and we should check the rest of its second argument recursively.

Upvotes: 2

wonce
wonce

Reputation: 1921

You can use the existing function elem http://hackage.haskell.org/package/base-4.7.0.0/docs/Prelude.html#v:elem

check x ls
    | x `elem` ls = ls
    | otherwise   = (x:ls)

If you want to do it completely on your own for learning purpose, I suggest re-implementing elem.

Upvotes: 6

Related Questions