• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

sorting and merging terms with haskell

Jjoshua2

Senior member
so defined a type called term which is a coffecient and degree of x. int a int b.
I want to write a method/methods in haskell to sort them and combine ones with same degree. I think I need to combine somehow, and then use sortby method? I'm just learning haskell, but I now java and c# pretty well and I'm having a hard term converting to functional thinking.
its of type [(Int a Int b)] and if b1< b2 put tuple 1 before tuple2, else if = combine by adding a1 to a2, else place 2 before 1

I tried something like this based on an example but its pretty random:
sortby xxx [(Term a b) : (Term c d) : xs]
xxx | b < d = LG
| b > d = RG
 
Last edited:
First you write a function which compares two terms by degree: call it compareDegrees. Then you use the standard library function named sortBy with your custom comparison function: sortBy compareDegrees list.

There is also a handy standard function named groupBy that will produce a list of lists where all "equal" consecutive elements are put in each list. The first parameter to groupBy is supposed to be a function which decides what is considered "equal".

I hope that gets you started on what sounds like a HW assignment and remember that you should be playing around using the interpreter to test ideas before putting it into your program and trying to compile it.
 
Thanks!
something like this seems it should work, however the list of lists is not what I wanted. Is it possible to add to the sortby instructions for when b = d? I want combined term of a+c d instead of a list with the two terms.
first call sortby using
compareDegrees (Term a b) (Term c d) = compare b d
then go through the list
combine (Term a b) : (Term c d) : xs =
if b = d
combine Term a+c d : xs
else combine (Term c d) : xs
 
That is a good start for a recursive definition of combine. You are missing two things that I can see. First, you need parentheses around the pattern so the compiler knows you are talking about only one parameter instead of multiple arguments. Second, in the else branch, you are dropping Term a b on the floor. Make sure that it ends up in the returned list.

And of course you need to define pattern matches for single and zero element lists, the base cases.
 
Back
Top