开发者

Define a remove function

I'm having trouble with this exercise, please help !

Define a function remove that takes an integer and a list of integers as input and returns the list obtained by deleting the 开发者_JAVA百科first occurrence of the integer in the list;

delete :: Int -> [Int] -> [Int]


I'm learning Haskell, so my answer is not authoritative. Rather than posting the code that I've written to answer you question, I try to write the way I looked at the problem.

I approached it looking at the various cases (I've found that this helps with Haskell):

  1. deleting whatever from an empty list ... that's easy

  2. deleting something (x) from a non-empty list (ys):

    2.1. is x equal to the first element of ys? then I'm done ...

    2.2. otherwise I just have to delete x from the list starting after the first element of ys


Think about delete as building a new list without the element in question, rather than removing the element itself. (sounds like homework so I'll be no more specific than that :))


Sorry to give away the answer, but here it is, straight from the source of Data.List

delete :: (Eq a) => a -> [a] -> [a]
delete = deleteBy (==)

deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
deleteBy _  _ []     = []
deleteBy eq x (y:ys) = if x `eq` y then ys else y : deleteBy eq x ys

Normally I'd describe it here, but if you understand basic recursion, if statements, pattern matching, and the : operator, and partial application/currying, then it should be self-explanatory. Feel free to ask if any one of these is foreign to you.


first: declare the function (look up how function declarations work) - depending on language it looks similar to this:

array
delete( int input1, array input2 )
{
}

then work on the body of the function

declare tha variables you need, perform the array manipulation return the resulting array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜