Haskell 程式初始化並列印複數


本教程將幫助我們初始化並列印一個複數。在 Haskell 中,Data.Complex 庫提供了一個 Complex 型別來表示複數。

方法 1:使用 Complex 資料型別

此方法定義了一個 Complex 資料型別,它儲存複數的實部和虛部,以及 Complex 的 Show 型別類的例項,這允許使用 putStrLn 函式列印它。

在 main 函式中,它建立了一個具有實部和虛部的複數物件。然後它使用 putStrLn 函式和 show 函式列印複數。

演算法

  • 步驟 1 − 定義 Complex 資料型別,它將儲存複數的實部和虛部。

  • 步驟 2 − 定義 Show 例項以表示複數。

  • 步驟 3 − 程式執行將從 main 函式開始。main() 函式控制整個程式。它寫成 main = do。

  • 步驟 4 − 初始化一個名為“c”的變數。它將具有要表示為複數的實數和虛數值。

  • 步驟 5 − 使用“putStrLn”語句顯示最終的複數值。

示例

使用 Complex 資料型別初始化並列印複數的程式。

data Complex = Complex { real :: Double, imag :: Double }
instance Show Complex where
   show (Complex r i) = (show r) ++ " + " ++ (show i) ++ "i"
main :: IO ()
main = do
   let c = Complex { real = 3.0, imag = 4.0 }
   putStrLn $ "The complex number is: " ++ (show c)

輸出

The complex number is: 3.0 + 4.0i

方法 2:使用帶建構函式和型別類的自定義資料型別

在此方法中,定義了一個自定義資料型別 Complex,它帶有一個建構函式,該建構函式接收兩個雙精度值,分別表示複數的實部和虛部。定義了 ComplexNumber 型別類,它具有 3 個函式 real、imag 和 toString,用於訪問實部和虛部,並將其轉換為字串。為 Complex 資料型別定義了 ComplexNumber 型別類的例項。putStrLn 函式用於使用 toString 函式列印複數。

演算法

  • 步驟 1 − 定義自定義資料型別 Complex 以儲存實部和虛部。

  • 步驟 2 − 定義 ComplexNumber 型別類,它具有 3 個函式 real、imag 和 toString,用於訪問實部和虛部,並將其轉換為字串。

  • 步驟 3 − 使用以上三個函式為 Complex 資料型別定義 ComplexNumber 型別類的例項。

  • 步驟 4 − 程式執行將從 main 函式開始。main() 函式控制整個程式。

  • 步驟 5 − 初始化一個名為“c”的變數。它將具有要以複數形式表示的實數和虛數值。

  • 步驟 6 − 使用“putStrLn”語句顯示最終的複數值。

示例 1

使用帶建構函式和型別類的自定義資料型別初始化並列印複數的程式。

data Complex = Complex Double Double deriving Eq
class ComplexNumber a where
   real :: a -> Double
   imag :: a -> Double
   toString :: a -> String
instance ComplexNumber Complex where
   real (Complex r _) = r
   imag (Complex _ i) = i
   toString c = (show $ real c) ++ " + " ++ (show $ imag c) ++ "i"
main :: IO ()
main = do
   let c = Complex 3.0 4.0
   putStrLn $ "The complex number is: " ++ (toString c)

輸出

The complex number is: 3.0 + 4.0i 

示例 2

在此示例中,使用元組表示複數,其中第一個元素是實部,第二個元素是虛部。putStrLn 函式用於列印複數,該複數使用 show 函式自動轉換為字串。

type Complex = (Double, Double)
main :: IO ()
main = do
   let c = (3.0, 4.0)
   putStrLn $ "The complex number is: " ++ (show c)

輸出

The complex number is: (3.0,4.0)

結論

在 Haskell 中,可以透過多種方法將數字初始化並列印為複數,包括 Complex 資料型別、帶建構函式和型別類的自定義資料型別或使用元組等。

在每種方法中,都會傳遞需要以複數形式表示的實部和虛部。

更新於: 2023年1月19日

190 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

立即開始
廣告

© . All rights reserved.