Stephanie
Stephanie

Reputation: 11

Haskell Programming simple function recurrsion

for this program an element and a list is taken in and a new list is returned. if there are any occurrences of the element in the list, they should be deleted in the list that is returned.

allOcrDelete :: Eq a => a -> [a] -> [a]

allOcrDelete del = if head [a] == number then allOcrDelete(tail [a])
               else del ++ [head [a]] ++ allOcrDelete(tail [a])

this is what i have so far. i'm not sure how to take an element and a list as parameters and how to take the head or tail and compare the head to the element to be deleted

Upvotes: 0

Views: 103

Answers (2)

leftaroundabout
leftaroundabout

Reputation: 120751

First let me say, don't use head and tail, ever. ...Well, at least not until you've gathered so much experience that you can recognise the few cases when it actually makes something more concise. Usually pattern matching (or folding etc.) is not only much safer but also far more readable & intuitive.

So in your case, you're trying to get head [a]. What is [a]? You evidently mean, “the argument of the function which has type [a], but that's not possible to write in Haskell code. (What if there was yet another element of the same type?) To use an argument, you have to _bring it in scope, with some arbitrary name (only, names can't contain brackets), e.g.

delete' del xs = if head xs == number then delete'(tail xs)
                  else del ++ [head xs] ++ delete'(tail xs)

would work. (Sort of. number also doesn't make sense there: you probably want to compare with del, instead of inserting that.)

However, since the only thing you do with xs is call those evil head and tail functions, you should rather write it this way:

delete' del (x:xs) = if x == number then delete' xs
                      else del ++ [x] ++ delete' xs

Upvotes: 2

zigazou
zigazou

Reputation: 1755

As jamshidh mentioned, you can use filter and write:

allOcrDelete del = filter (/= del)

(allOcrDelete is a special case of filter)

A naive implementation could be:

module Main where

allOcrDelete :: Eq a => a -> [a] -> [a]
allOcrDelete _ [] = []
allOcrDelete del (x:xs)
    | del == x  =   allOcrDelete del xs
    | otherwise = x:allOcrDelete del xs

main = do
    print $ allOcrDelete 2 [1,2,5,3,2,4,5,2]

Note:

  • you don't need to use the head and tail functions in this case because pattern matching the list against (x:xs) will already split the list into the head x and the tail xs (this is a common pattern in Haskell)

Upvotes: 4

Related Questions