Haskell: Stuck writing function to replicate `elem`

For my first lecture at haskell, we asked a number of problems. One of them is to return True when n is present in the list or False otherwise. I managed to get what, in my opinion, halfway, but I get different compilation errors and get quite tired because I can even understand what they mean.

So far I have done the following

// No problem with this function
matches :: Int -> [Int] -> [Int]    // This function is to return the matches 
matches x y = [a | a <-y, a==x]     // ie. main> 1 [1,3,5,7,1,4] outputs [1,1]

// Here am stuck
myelem :: Int -> [Int] -> Bool
myelem x [] = False
myelem x (y:ys)
 | x == y = y : x myelem ys       // Am not sure about recursion as 
                                  // we have not yet covered

Obviously this is for the class, so please do not post the answer. But maybe a few examples that will help me justify how Haskell works and how to approach the problem. Any pointer would be widely appreciated.


Decision

matches :: Int -> [Int] -> [Int]
matches x y = [a | a <-y, a==x]

myelem :: Int -> [Int] -> Bool
myelem x [] = False
myelem x (y:ys)
 | x == y = True
 | otherwise = myelem x (ys)

Greetings guys

+3
source share
5 answers

:

myelem x (y:ys)
 | x == y = y : x myelem ys

:

  • myelem , backticks, :

    x `myelem` ys
    
  • , , ; (:) , , Bool. , (:) , myelem Bool!

, . x == y, True, ? otherwise, (ys). , .

+2

. . , myelem , infix (x `myelem` ys) (myelem x ys). , y . : , myelem x (y:ys) , .

+1

Int Bool ; .

True myelem; .

.

+1

, ( , ):

filter :: (a -> Bool) -> [a] -> [a]

,

null :: [a] -> Bool

not :: Bool -> Bool

-

or :: [Bool] -> Bool

True, Bool True.

, , .

+1

, myelem matches.

  • , ?
  • , ? ? ?
  • ? (: )
0

Source: https://habr.com/ru/post/1793185/


All Articles