Haskell 101

February 4, 2008

Matching items

Filed under: Functional programming, Guards, Haskell, Pattern matching, Recursion — Haskell 101 blogger @ 8:02 pm

So far, we have created a function that determine whether a given item appears in a list, and another that counts how many times a given item appears in a list. Now let’s create one that returns a complete list of all items from a given list that match a given item. In other words, we have a list y and want to get a list of all items in y that match a given item x.We want a function that takes an integer and a list, and returns a list. 

(1) matches::Int->[Int]->[Int]

 As we did with our instances function, we start with the case that ends a recursion. 

(2) matches x [] = []

 For the other cases, we’ll mimic the structure from our instances function. This time, though, instead of adding one to the total, we’ll simply add the matching item to the list we’re collecting. 

(3) matches x (y:ys)
	| x==y = x:(matches x ys)
	| otherwise = matches x ys



Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: