pattern matching - Haskell: Stuck writing a function to replicate`elem` -


for first lecture in haskell given series of problems. 1 of them return true when n number present in list, or false otherwise. managed think half-way there getting different compile errors , pretty frustated because can understand mean.

so far have done following

// no problem function matches :: int -> [int] -> [int]    // function return matches  matches x y = [a | <-y, a==x]     // ie. main> 1 [1,3,5,7,1,4] outputs [1,1]  // here stuck myelem :: int -> [int] -> bool myelem x [] = false myelem x (y:ys)  | x == y = y : x myelem ys       // not sure recursion                                    // have not yet covered 

obviously class please not post answer. maybe few examples me reason both workings of haskell , how approach problem. pointer massively appreciated.


solution

matches :: int -> [int] -> [int] matches x y = [a | <-y, a==x]  myelem :: int -> [int] -> bool myelem x [] = false myelem x (y:ys)  | x == y = true  | otherwise = myelem x (ys) 

cheers guys

the problem in last equation:

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

there 2 problems here:

  1. if want use myelem infix operator, have surround in backticks, so:

    x `myelem` ys 
  2. given that's meant, right hand side of equation doesn't type check; list constructor (:) requires second argument list, not bool. furthermore, (:) constructs list, , myelem supposed return bool!

think you're trying do. if x == y, want return true, right? , otherwise, want return result of checking rest of list (ys). hope helps.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -