Skip to content

Instantly share code, notes, and snippets.

@akoskovacs
Last active December 14, 2015 08:29
Show Gist options
  • Save akoskovacs/5057795 to your computer and use it in GitHub Desktop.
Save akoskovacs/5057795 to your computer and use it in GitHub Desktop.
N00b Haskell Matrix library (unready)
module Main where
import System.Environment (getArgs)
import Data.List
import Matrix
import IO
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
a <- putStr "Add meg a file nevét: "
fileName <- getLine
putStr "Add meg a kvadratikus mátrix méretét: "
size <- getLine
file <- openFile fileName WriteMode
hPutMatrix file (identityMatrix (read size))
hClose file
return ()
module Matrix where
import Data.List
import IO
identityMatrix :: Int -> [[Int]]
identityMatrix 0 = [[]]
identityMatrix n = [identityVector n x | x <- [1..n]]
identityVector :: Int -> Int -> [Int]
identityVector x n = [if a == n then 1 else 0 | a <- [1..x]]
checkMatrix :: [[a]] -> Bool
checkMatrix m = and (map (== (head rowLengths)) (tail rowLengths))
where
rowLengths = map length m
isQuadratic :: [[a]] -> Bool
isQuadratic m | checkMatrix m
= length m == length (m !! 0)
{-
- Determinant of a 2 by 2 matrix.
- Ex.: det2x2 [[0,1],[1,0]] -- => 1
-}
det2x2 :: [[Int]] -> Int
det2x2 m | isQuadratic m && length m == 2
-- a*d - b*c
= (m !! 0 !! 0) * (m !! 1 !! 1)
- (m !! 0 !! 1) * (m !! 1 !! 0)
matrixRowAndCol :: [[Int]] -> (Int, Int)
matrixRowAndCol m | checkMatrix m
= (length m, length (m !! 0))
-- Impure functions
hPutVector :: Handle -> [Int] -> IO ()
hPutVector h v = hPutStr h (intercalate " " (map show v))
hPutMatrix :: Handle -> [[Int]] -> IO ()
hPutMatrix h [] = return ()
hPutMatrix h (x:xs) = do
hPutVector h x
hPutChar h '\n'
hPutMatrix h xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment