Bookmark and Share

Journal

Entering multi-line code in GHCi

Use :{ and :} to sandwich a block of code consisting of multiple lines:

Prelude> :{
Prelude| incrementInteger :: Int -> Int
Prelude| incrementInteger x = x + 1
Prelude| :}
Prelude> incrementInteger 1
2

Using the latest released version of GHC with stack

Specify the version of LTS (i.e. Long Term Support) Haskell to use by default in `$HOME/.stack/global-project/stack.yaml:

resolver: lts-8.15

As of May, 2017, the newest released version of LTS Haskell is 8.15. This version number can be found on https://www.haskell.org/downloads.

data, type, and newtype

  • https://stackoverflow.com/a/33316715

  • In GHCi, print the type of a symbol

      Prelude> :type Nothing
      Nothing :: Maybe a
      Prelude> :type (+)
      (+) :: Num a => a -> a -> a
      Prelude> :type print "Hello World"
      print "Hello World" :: IO ()
    

Nothing and Maybe

Partial application

Functions are not partial, but rather a function can be applied partially.

Function type decalaration

myFunc :: type1 -> type2 -> type3 -> type4

Pure as in 'pure functional programming languages'

Get information about a Haskell word in GHCi

Prelude> :info pure
class Functor f => Applicative (f :: * -> *) where
  pure :: a -> f a
  ...
    -- Defined in ‘GHC.Base’

Concatenating multiple strings into one using intercalate, intersperse and concat, and unword.

Function application takes precedence over any binary operator.

For example,

ourPicture = colored green (solidCircle 1) & solidCircle 2

is equivalent to

ourPicture = (colored green (solidCircle 1)) & (solidCircle 2)

guard

Changing a prefixing function to an infix binary operator

Prelude> mod 3 2
1
Prelude> 3 `mod` 2
1

Largest integer

Prelude> :{
Prelude| myInt :: Int
Prelude| myInt = 2^63 - 1
Prelude| :}
Prelude> myInt
9223372036854775807
Prelude> myInt + 1
-9223372036854775808

Prelude> :{
Prelude| minInt :: Int
Prelude| minInt = - 2^63
Prelude| :}
Prelude> minInt
-9223372036854775808
Prelude> minInt - 1
9223372036854775807

Arithmetic expression with different types of numbers

Prelude> :{
Prelude| d :: Double
Prelude| i :: Int
Prelude| d = 1.2
Prelude| i = 1
Prelude| :}
Prelude> d+i

<interactive>:48:3: error:
    • Couldn't match expected type ‘Double’ with actual type ‘Int’
    • In the second argument of ‘(+)’, namely ‘i’
      In the expression: d + i
      In an equation for ‘it’: it = d + i
Prelude> d + fromIntegral i
2.2
Prelude>

References

  • https://www.stackage.org
    • Lookup basic information about a word, e.g. pure: https://www.stackage.org/lts-8.15/hoogle?q=pure
blog comments powered by Disqus