Display a linear combination: Difference between revisions
Content added Content deleted
(Add Rust implementation) |
(→{{header|Haskell}}: added solution) |
||
Line 733: | Line 733: | ||
[-1, -2, 0, -3] -> -e(1) - 2*e(2) - 3*e(4) |
[-1, -2, 0, -3] -> -e(1) - 2*e(2) - 3*e(4) |
||
[-1] -> -e(1)</pre> |
[-1] -> -e(1)</pre> |
||
=={{header|Haskell}}== |
|||
<lang haskell>import Text.Printf (printf) |
|||
linearForm :: [Int] -> String |
|||
linearForm = strip . concat . zipWith term [1..] |
|||
where |
|||
term :: Int -> Int -> String |
|||
term i c |
|||
| c == 0 = printf "" |
|||
| c == 1 = printf " + e(%d)" i |
|||
| c > 0 = printf " + %d*e(%d)" c i |
|||
| c == -1 = printf " - e(%d)" i |
|||
| c < 0 = printf " - %d*e(%d)" (-c) i |
|||
strip str = case str of |
|||
' ':'+':' ':s -> s |
|||
' ':'-':' ':s -> '-':s |
|||
"" -> "0" |
|||
s -> s</lang> |
|||
Testing |
|||
<lang haskell>coeffs :: [[Int]] |
|||
coeffs = [ [1, 2, 3] |
|||
, [0, 1, 2, 3] |
|||
, [1, 0, 3, 4] |
|||
, [1, 2, 0] |
|||
, [0, 0, 0] |
|||
, [0] |
|||
, [1, 1, 1] |
|||
, [-1, -1, -1] |
|||
, [-1, -2, 0, -3] |
|||
, [-1] ]</lang> |
|||
<pre>λ> mapM_ (print . linearForm) coeffs |
|||
"e(1) + 2*e(2) + 3*e(3)" |
|||
"e(2) + 2*e(3) + 3*e(4)" |
|||
"e(1) + 3*e(3) + 4*e(4)" |
|||
"e(1) + 2*e(2)" |
|||
"0" |
|||
"0" |
|||
"e(1) + e(2) + e(3)" |
|||
"-e(1) - e(2) - e(3)" |
|||
"-e(1) - 2*e(2) - 3*e(4)" |
|||
"-e(1)"</pre> |
|||
=={{header|J}}== |
=={{header|J}}== |