Skip to content

Instantly share code, notes, and snippets.

@m-renaud
Created November 22, 2014 09:29
Show Gist options
  • Save m-renaud/b15f675389fb5d6eda50 to your computer and use it in GitHub Desktop.
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 :)
{-# 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)
{-# 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