在 haskell 的 Poly 包中,像 x**2 -1 這樣的多項式由 [ -1, 0, 2] 表示,因此為了計算多項式的次數,我需要計算多項式串列的長度 - 1。
這就是我所做的:
polyDegree :: (Num a, Eq a) => Poly a -> Int
polyDegree p = rawPolyDegree (trim (0==) p)
rawPolyDegree :: Poly a -> Int
rawPolyDegree p = rawPolyLength p - 1
rawPolyLength :: Poly a -> Int
rawPolyLength (ListPoly _ _ cs) = length cs
rawPolyLength (VectorPoly _ _ cs) = V.length cs
rawPolyLength (UVectorPoly _ _ cs) = UV.length cs
我試圖編譯這段代碼。但不起作用此代碼輸出此錯誤
? ghc -o main main.hs
[1 of 1] Compiling Main ( main.hs, main.o )
main.hs:1:32: error: Not in scope: type constructor or class `Poly'
|
1 | polyDegree :: (Num a, Eq a) => Poly a -> Int
| ^^^^
main.hs:4:18: error: Not in scope: type constructor or class `Poly'
|
4 | rawPolyDegree :: Poly a -> Int
| ^^^^
main.hs:7:18: error: Not in scope: type constructor or class `Poly'
|
7 | rawPolyLength :: Poly a -> Int
| ^^^^
main.hs:8:16: error: Not in scope: data constructor `ListPoly'
|
8 | rawPolyLength (ListPoly _ _ cs) = length cs
| ^^^^^^^^
main.hs:9:16: error: Not in scope: data constructor `VectorPoly'
|
9 | rawPolyLength (VectorPoly _ _ cs) = V.length cs
| ^^^^^^^^^^
main.hs:9:39: error:
Not in scope: `V.length'
No module named `V' is imported.
|
9 | rawPolyLength (VectorPoly _ _ cs) = V.length cs
| ^^^^^^^^
main.hs:10:16: error: Not in scope: data constructor `UVectorPoly'
|
10 | rawPolyLength (UVectorPoly _ _ cs) = UV.length cs
| ^^^^^^^^^^^
main.hs:10:38: error:
Not in scope: `UV.length'
No module named `UV' is imported.
|
10 | rawPolyLength (UVectorPoly _ _ cs) = UV.length cs
| ^^^^^^^^^
exit status 1
我在堆疊溢位中研究了編譯 haskell 函式的問題 ,我在這里發現了一個關于簡單代數函式的問題我明白我的問題是我沒有指示 Haskell 程式應該做什么這個問題的答案是這樣的:
main :: IO ()
main = print (f 2)
因此,根據問題需要將其放在我的代碼中的某個位置,但我不知道如何將這個函式的值放在哪里?
I am studying with Programming in Haskell 2016 Graham Hutton 2nd Edition the book said is not important learn how to compile the snippets but I want to compile this snippets for check if my code is running. I am new in haskell, I am learning and interested in functional paradigm. I am using GHCi, version 8.6.5 Online Compiler for this.
uj5u.com熱心網友回復:
我沒有讀過這本書,但我的印象是它不打算讓您在這里使用第三方軟體包。
相反,直接使用 list。型別[k]和長度為n 的串列可以表示具有n個型別系數的多項式k,按照從最不重要 ( x 0 ) 到最重要 ( x ( n ? 1) ) 的順序。那么計算度數的一種方法就像你說的,只是這樣一個串列的長度減去一個:
degree :: [a] -> Int
degree p = length p - 1
你可以通過引入你自己的型別同義詞來重新表述:
type Poly a = [a]
degree :: Poly a -> Int
degree p = length p - 1
此解決方案有一些錯誤,例如:
如果
degree給出一個空[]的系數串列會發生什么?會發生什么?應該
degree [1, 0, 0]評價什么?會發生什么?(這就是為什么您復制的代碼也需要(Num a, Eq a)。)
在您從poly包中復制的代碼中,類似函式rawPolyLength對庫的資料表示進行操作,也稱為Poly. 對于不同的表示(串列、裝箱向量和未裝箱向量),它有幾個不同的建構式。您尚未在代碼中定義類似的內容。如果您想練習定義對串列進行操作的函式,只需使用[a],或者添加type Poly a = [a]并使用您自己的Poly a. 您可以使用 的函式ListPoly作為如何在普通串列上定義這些相同操作的參考,代碼不會完全相同。
與其他語言一樣,您可以使用外部包,就像poly您想使用多項式的實作而不必自己定義它們一樣。對于學習 Haskell,建議最初堅持使用base包 ( Prelude, Data.List, &c.) 以熟悉語言的核心詞匯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/337042.html
標籤:haskell math functional-programming polynomials algebra
下一篇:在Python中回傳一個類的實體
