Saturday 30 April 2016

Haskell: How to enable GHC extensions


GHC implements some extensions to the Haskell language. By using command line flags or language pragmas, you can enable (or) disable these extensions.

Enable extensions using command line arguments
You can enable an extension by passing command-line flag -XExtensionName to the GHCi command line utilities ghc, ghci, or runghc.

Language Pragma
The LANGUAGE pragma allows language extensions to be enabled in a portable way.

Syntax
{-# LANGUAGE extension1, extension2 ... extensionN #-}

You need to add above line at the starting of your Haskell file.

{-# LANGUAGE ForeignFunctionInterface, CPP #-} : Enables the FFI and preprocessing with CPP

{-# LANGUAGE BangPatterns #-} : Enables Bang patterns

Following Haskell file uses Bang pattern.

listUtil.hs
{-# LANGUAGE BangPatterns #-}
sumList :: [Integer] -> Integer
sumList xs = sumOfEle xs 0

sumOfEle :: [Integer] -> Integer -> Integer
sumOfEle [] acc = acc
sumOfEle (x:xs) !acc = sumOfEle xs (acc+x)

main = print (sumList [1..1000000])

*Main> :load listUtil.hs
[1 of 1] Compiling Main             ( listUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> main
500000500000


References

Previous                                                 Next                                                 Home

No comments:

Post a Comment