Last active
August 29, 2015 14:09
-
-
Save m-renaud/0b4aa29e8c3187ae63f1 to your computer and use it in GitHub Desktop.
Simple Matrix addition in Haskell.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE TemplateHaskell #-} | |
module MatrixDemo where | |
import Control.Lens | |
-- | Represents a matrix with the contents stored in row major order. | |
-- Note that we get equality, ability to read a Matrix from a stream | |
-- as well as write it to a stream for free by deriving (Eq,Read,Show). | |
data Matrix = Matrix { _numRows :: Int | |
, _numColumns :: Int | |
, _matrixContents :: [[Int]] | |
} deriving (Eq,Read,Show) | |
makeLenses ''Matrix | |
-- | Construct a Matrix from a list of rows. | |
toMatrix :: [[Int]] -> Matrix | |
toMatrix m = Matrix { _numRows = length m, _numColumns = length (head m), _matrixContents = m } | |
-- | Takes two matricies 'a' and 'b' and returns a new matrix obtained by taking | |
-- the matrix a and applying the function addCorresponding entries to it's contents. | |
-- The function addCorrespondingEntries simply overlays the two list of lists and | |
-- sums the corresponding elements. | |
add :: Matrix -> Matrix -> Matrix | |
add a b = a & over matrixContents addCorrespondingEntries | |
where addCorrespondingEntries = (zipWith (zipWith (+)) (b^.matrixContents)) | |
main = do | |
let a = toMatrix [[1,2,3],[4,5,6]] | |
let b = toMatrix [[1,1,1],[2,2,2]] | |
print $ add a b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment