You are viewing a single comment's thread from:

RE: Coding Challenge #2 – Polynomial

in #coding-challenge7 years ago

I've only implemented the parsing. The code is accessible at https://repl.it/KQWN. Since I used a parsec library, you cannot run it there. :/

I don't parse the variable names, so it's possible to use multiple variables mistakenly.

poly.png

Sort:  

This is pretty cool! Can you elaborate a bit on what language you used, how you build up the grammar etc.?

There are three parsers related to polynomials: poly term and number.

Line 15: All parsers remove the trailing spaces, so the main parser poly should remove the leading whitespace. It basically states: skip the whitespace, poly is made of many terms and you arrive to the end of the input.

Line 18: term is a tuple of a number and another number. The second number is located after an identifier and the symbol ^.

Line 21-25: number is either negative or positive. <|> stands for either. For the second case the number may not start with the sign +, option takes care of that. f computes the value of the string of numbers.

Line 28: We run the parser poly on the sample input. It prints out the result as a tuple of terms as indicated in the parser descriptions.

Thank you for the explanation! Parsec is really strong, looking forward to leaning more about it :)

It is and I'm using it in very basic form. There're very good documents at https://github.com/haskell/parsec

I implemented showPoly, add, subtractPoly, and multiply functions.

poly2.png

Oh snap, the simplify looks crazy! It would be so cool if you could make a post explaining how each little piece works in many details, once you are finished.

There are basically three transformations.

  1. sortOn snd poly
    poly is a list of tuples of two numbers for each polynomial term's coefficient and power. First step sorts the list of tuple by its second element which is power.
  2. groupBy ...
    We group all terms by their power. groupBy returns a list of lists. Each list represent a power value.
  3. map f
    For each list of lists we foldl the list which is basically reducing the list to a single value. For instance if we have 5x^2-3x^2+x^2 it evaluates to 3x^2.

Once you get used to functional programming, most things will look very clear. ;)
Take a look: http://learnyouahaskell.com

I would agree.

beep loves coding ? :D

I think this is Functional Programming.....
looks like Haskell or F#... not sure.

Checking the author is is most likely Haskell, that was the language he submitted the last challenge in.

It's Haskell. The links provide the information but it wasn't clear at first sight.

Coin Marketplace

STEEM 0.20
TRX 0.26
JST 0.039
BTC 99772.57
ETH 3596.28
USDT 1.00
SBD 3.10