Created
November 22, 2014 09:29
-
-
Save m-renaud/b15f675389fb5d6eda50 to your computer and use it in GitHub Desktop.
Sum of squares. This contains two versions, one using Vector and another that takes advantage of stream fusion. The stream fusion version is sightly faster and uses constant space. You'll ALSO notice, the only difference between the two files is the 3rd import statement :)
This file contains hidden or 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 BangPatterns #-} | |
{-# OPTIONS_GHC -Odph #-} | |
import Prelude hiding (map, sum) | |
import qualified Data.ByteString.Char8 as S | |
import Data.List.Stream | |
main = S.getContents >>= print . sumOfSquares . parse | |
where sumOfSquares = sum . map (\x -> x * x) | |
-- Fill a new vector from a file containing a list of numbers. | |
parse = unfoldr step | |
where | |
step !s = case S.readInt s of | |
Nothing -> Nothing | |
Just (!k, !t) -> Just (k, S.tail t) |
This file contains hidden or 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 BangPatterns #-} | |
{-# OPTIONS_GHC -Odph #-} | |
import Prelude hiding (map, sum) | |
import qualified Data.ByteString.Char8 as S | |
import Data.Vector | |
main = S.getContents >>= print . sumOfSquares . parse | |
where sumOfSquares = sum . map (\x -> x * x) | |
-- Fill a new vector from a file containing a list of numbers. | |
parse = unfoldr step | |
where | |
step !s = case S.readInt s of | |
Nothing -> Nothing | |
Just (!k, !t) -> Just (k, S.tail t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment