我剛剛了解了haskell,但我對型別資料有疑問,我有如下型別資料
[Test {name = "name1", Address = "Address1", Score = 80},Test {name = "name2", Address = "Address2", Score = 60}]
我的問題是如何分開=
Name Address Score Pass
-------------------------
name1 Address1 80 Y
name2 Address2 60 N
我試過了
printArray :: [Test] -> IO()
printArray [Test x y z] = do
putStr x
putStr (" " y)
putStr (" " show z)
if z >= 70 then putStrLn " Y"
else putStrLn " N"
但是當我執行時出現錯誤:函式 printArray 中的非詳盡模式
提前致謝
uj5u.com熱心網友回復:
這里沒有任何陣列。[]用于串列。
您的代碼無法解決問題的原因printArray [Test x y z] = ...是它只匹配串列中只有一個元素的情況。如果您想對所有元素執行此操作,您可以使用
遞回。
printTests (Test x y z : tests) = do putStr x putStr (" " y) putStr (" " show z) putStrLn $ if z >= 70 then " Y" else " N" printTests tests printTests [] = return ()一個標準的回圈組合器
printTests = mapM_ $ \(Test x y z) -> do ......或者,也許更容易理解
import Control.Monad (forM_) printTests tests = forM_ tests $ \(Test x y z) -> do ...(推薦)分離你的關注點:不要在回圈設定中做討厭的 IO,從簡單開始
showTest :: Test -> String然后
putStrLn (unlines $ map showTest tests)在實際需要列印的地方使用。
uj5u.com熱心網友回復:
這是錯誤的。您對僅包含一個元素 [Test xyz] 的單例串列進行模式匹配。
printArray :: [Test] -> IO ()
printArray [] = pure ()
printArray (Test x y z : xs) = do
putStr x
putStr (" " y)
putStr (" " show z)
if z >= 60
then putStrLn " Y"
else putStrLn " N"
printArray xs
uj5u.com熱心網友回復:
拆分它:
printTest :: Test -> IO()
printTest (Test x y z) = do
putStr x
putStr (" " y)
putStr (" " show z)
if z >= 60
then putStrLn " Y"
else putStrLn " N"
printArray :: [Test] -> IO()
printArray [] = pure ()
printArray (t:ts) = do
printTest t
printArray ts
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/427280.html
標籤:哈斯克尔
