[Haskell-cafe] help with a question
Michael Vanier
mvanier42 at gmail.com
Tue Jun 9 20:53:02 EDT 2009
haonan21 wrote:
> I'm very new to haskell hugs and would appreciate it if someone could help me
> out here. I've been giving 2 questions.
>
> 1.) A and B are two sets of integers. Implement a function to obtain the
> integers that belong to both sets.
> Test your function fully.
>
> 2.) Define and test a function f, which, if A is a set of {x, y, z} then
> f(A) = {{},{x}, {y}, {z}, {x, y}, {x,z}, {y,z}, {x, y, z}}
>
> Manage to get the first one.
> interset::[Int]->[Int]->[Int]
>
> interset x [] = []
>
> interset [] y = []
>
> interset x@(xs:xt) y@(ys:yt) =
> if xs == ys
> then as:(interset at yt)
> else interset at y
>
> Totally have no clue for the 2nd question. could someone help me out ?
>
> Many thanks!
>
Haonan,
This looks like homework, but I can offer a few suggestions. Your
"interset" function uses "as" and "at" where I think you mean "xs" and
"xt" and the else case is wrong (you need to test the code!). Anyway,
it looks like you're assuming that the lists are in ascending order, and
I don't see that in the problem specification -- it won't work if that
isn't the case. More interestingly, you should look at the List (or
Data.List) library; it contains a library function which can solve your
problem in one line. As for the second function, that's a classic
problem used for teaching recursion: find all subsets of a given list.
The way to solve it is to first ask what the solution is for the empty
set (which should be obvious). Then assume that you have the solution
for the tail of the list ({y, z}). How would you use this and the head
of the list (x) to generate the full solution?
HTH,
Mike
More information about the Haskell-Cafe
mailing list