簡體   English   中英

Haskell 如何顯示函數結果

[英]Haskell how can I show function result

我有一個問題要求我找到“二次方程”並show結果並添加根數

例子:

Main> quadratric 2 2 2
2x^2 + 2x + 2 = 0
Has no real roots.

Main> quadratic 2 5 2
2x^2 + 5x + 2 = 0
Has two real roots:
-2.0 and -0.5

所以這是二次方程:

quadraticprob a b c
       | root < 0  = error "Has no real roots"
       | root == 0 = [-b/(2*a)]
       | root > 0  = [-b/(2*a) + sqroot/(2*a),
                             -b/(2*a) - sqroot/(2*a)]
       where
           root = b*b - 4*a*c
           sqroot = sqrt root

我可以得到結果,但我應該加上它們有多少根,所以我應該再使用一個getLine函數並顯示結果。

我做了這個,但這是完全錯誤的:

readresult :: IO ()
readresult = do
      line <- getLine 
      putStrLn (show (quadraticprob (read line))

你能幫我解決我的錯誤嗎?

假設您想從標准輸入調用“getLine”函數一次獲取 3 個整數。

表達方式

line <- getLine

將返回一個字符串(例如)

"2 2 2"

每個整數之間有空格。 需要做的第一件事是刪除空格並將其從字符串轉換為 Int 類型。 wordsread函數可以很容易地解決這個問題,如下所示:

map read (words line)::[Int]

但是,整數列表不能直接傳遞給您的二次函數,它需要用從列表中獲取元素,如下所示

case map read (words line)::[Int] of 
     [a, b, c] -> putStrLn $ show $ quadraticprob a b c

如果您想讀取實數而不是整數,只需將 map..::[Int] 更改為 ::[Double]。

一些提示:

為每個參數使用getLine

... = do
   astr <- getLine
   bstr <- getLine
   cstr <- getLine
   putStrLn (show (quadraticprob (read astr) (read bstr) (read cstr)))

對於quadraticprob ,目前尚不清楚您的實際目標是什么。 在編寫任何代碼之前,您應該從編寫預期類型開始。

quadraticprob :: ?? -> ?? -> ?? -> ??

那應該是什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM