Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8507441
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T02:52:21+00:00 2026-06-11T02:52:21+00:00

I am representing sparse polynomials as lists of (coefficient, pairs). For example: ‘((1 2)

  • 0

I am representing sparse polynomials as lists of (coefficient, pairs). For example:

'((1 2) (3 6) (-20 48)) => x^2 + 3x^6 - 20x^48

I am new to Lisp formatting, but have come across some pretty nifty tools, such as (format nil "~:[+~;-~]" (> 0 coefficient)) to get the sign of the coefficient as text (I know, that’s probably not idiomatic).

However, there are certain display problems when formatting single terms. For example, the following should all be true:

(1 0) => 1x^0 => 1    (reducible)
(1 1) => 1x^1 => x    (reducible)
(1 2) => 1x^2 => x^2  (reducible)
(2 0) => 2x^0 => 2    (reducible)
(2 1) => 2x^1 => 2x   (reducable)
(2 2) => 2x^2 => 2x^2 (this one is okay)

I’m wondering if there’s a way to do this without a large series of if or cond macros – a way just to do this with a single format pattern. Everything works but the ‘prettifying’ the terms (the last line in FormatPolynomialHelper3 should do this).

(defun FormatPolynomial (p)
    "Readably formats the polynomial p."
    ; The result of FormatPolynomialHelper1 is a list of the form (sign formatted),
    ; where 'sign' is the sign of the first term and 'formatted' is the rest of the
    ; formatted polynomial. We make this a special case so that we can print a sign
    ; attached to the first term if it is negative, and leave it out otherwise. So,
    ; we format the first term to be either '-7x^20' or '7x^20', rather than having
    ; the minus or plus sign separated by a space.
    (destructuring-bind (sign formatted-poly) (FormatPolynomialHelper1 p)
        (cond
            ((string= formatted-poly "") (format nil "0"))
            (t                           (format nil "~:[~;-~]~a" (string= sign "-") formatted-poly)))))

; Helpers

(defun FormatPolynomialHelper1 (p)
    (reduce #'FormatPolynomialHelper2 (mapcar #'FormatPolynomialHelper3 p) :initial-value '("" "")))

(defun FormatPolynomialHelper2 (t1 t2)
    ; Reduces ((sign-a term-a) (sign-b term-b)) => (sign-b "term-b sign-a term-a"). As
    ; noted, this accumulates the formatted term in the variable t2, beginning with an
    ; initial value of "", and stores the sign of the leading term in the variable t1.
    ; The sign of the leading term is placed directly before the accumulated formatted
    ; term, ensuring that the signs are placed correctly before their coefficient. The
    ; sign of the the leading term of the polynomial (the last term that is processed)
    ; is available to the caller for special-case formatting.
    (list
        (first t2)
        (format nil "~@{~a ~}" (second t2) (first t1) (second t1))))

(defun FormatPolynomialHelper3 (tm)
    ; Properly formats a term in the form "ax^b", excluding parts of the form if they
    ; evaluate to one. For example, 1x^3 => x^3, 2x^1 => 2x, and 3x^0 => 3). The list
    ; is in the form (sign formatted), denoting the sign of the term, and the form of
    ; the term state above (the coefficient have forced absolute value).
    (list
        (format nil "~:[+~;-~]" (> 0 (first tm)))
        (format nil "~a~@[x^~a~]" (abs (first tm)) (second tm))))

EDIT: It’s correctly been stated that output should not contain logic. Perhaps I was asking too specific of a question for my problem. Here is the logic that correctly formats a polynomial – but I’m looking for something cleaner, more readable, and more lisp-idiomatic (this is only my third day writing lisp).

(defun FormatPolynomialHelper3 (tm)
    ; Properly formats a term in the form "ax^b", excluding parts of the form if they
    ; evaluate to one. For example, 1x^3 => x^3, 2x^1 => 2x, and 3x^0 => 3). The list
    ; is in the form (sign formatted), denoting the sign of the term, and the form of
    ; the term state above (the coefficient have forced absolute value).
    (list
        (format nil "~:[+~;-~]"   (> 0 (first tm)))
        (cond
            ((= 0 (second tm))      (format nil "~a" (abs (first tm))))
            ((= 1 (abs (first tm))) (cond
                ((= 1 (second tm))  (format nil "x"))
                (t                  (format nil "x^~a" (second tm)))))
            ((= 1 (second tm))      (format nil "~ax" (abs (first tm))))
            (t                      (format nil "~ax^~a" (abs (first tm)) (second tm))))))
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T02:52:23+00:00Added an answer on June 11, 2026 at 2:52 am

    Answer:

    I would not put this logic into FORMAT statements. Only if you want to encrypt your code or create more maintenance work for yourself. Good Lisp code is self-documenting. FORMAT statements are never self-documenting.

    Before printing I would first simplify the polynomial. For example removing every term which is multiplied by zero.

    ((0 10) (1 2)) -> ((1 2))
    

    Then if the multiplier is 1 can be tested in a normal COND or CASE statement.

    Also make sure that you never use CAR, CDR, FIRST, SECOND with a self-made data structure. The components of a polynomial should mostly be accessed by self-documenting functions hiding most of the implementation details.

    I would write it without FORMAT:

    Example code:

    (defun term-m (term)
      (first term))
    
    (defun term-e (term)
      (second term))
    
    (defun simplify-polynomial (p)
      (remove-if #'zerop (sort p #'> :key #'term-e)
                 :key #'term-m))
    
    (defun write-term (m e start-p stream)
      ; sign or operator
      (cond ((and (minusp m) start-p)
             (princ "-" stream))
            ((not start-p)
             (princ (if (plusp m) " + " " - ") stream)))
      ; m
      (cond ((not (= (abs m) 1))
             (princ (abs m) stream)))
      (princ "x" stream)
      ; e
      (cond ((not (= 1 e))
             (princ "^" stream)
             (princ e stream))))
    
    (defun write-polynomial (p &optional (stream *standard-output*))
      (loop for (m e) in (simplify-polynomial p)
            for start-p = t then nil
            do (write-term m e start-p stream)))
    

    Example use:

    CL-USER 14 > (write-polynomial '((1 2) (3 6) (-20 48)))
    -20x^48 + 3x^6 + x^2
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a large sparse matrix representing attributes for millions of entities. For example,
I am having big troubles representing a sparse matrix in C with a multi-list,
I have a graph representing users and some articles they wrote. I need to
I have a variable representing a bmp image with the following structure: image=[line1, line2,
I have a prototype representing a particual IFrame. That prototype have a function called
I have 3d-data representing the atmosphere. Now I want to interpolate this data to
I have a string representing an URL containing spaces and want to convert it
I have a string representing bits, such as: 0000101000010000 I want to convert it
I have a string representing a SQL query, and I need to extract the
I have string data representing locales, like fr or en. I need to convert

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.