i just learn about haskell but i've problem about Type Data, ihave type data like below
[Test {name = "name1", Address = "Address1", Score = 80},Test {name = "name2", Address = "Address2", Score = 60}]
my question is how to seperate to =
Name Address Score Pass
-------------------------
name1 Address1 80 Y
name2 Address2 60 N
i've try
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"
but when i executed i got error : Non-exhaustive patterns in function printArray
Thanks in advance
CodePudding user response:
There aren't any arrays here. [] is for lists.
The reason your code with printArray [Test x y z] = ... doesn't do the trick is that it only matches the case of a list with exactly one element in it. If you want to do this for all elements you can use either
Recursion.
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 ... ...or, perhaps easier to understand
import Control.Monad (forM_) printTests tests = forM_ tests $ \(Test x y z) -> do ...(Recommended) Separate your concerns: instead of doing nasty IO in a loop setting, start with simple
showTest :: Test -> StringAnd then use
putStrLn (unlines $ map showTest tests)where printing actually is needed.
CodePudding user response:
This is wrong. You pattern-match the singleton list containing just one element [Test x y z].
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
CodePudding user response:
Split it:
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
