Haskell Examples

Table of Contents

1 Haskell Vault Example

  • import package Data.Vault.Lazy
  • Create Empty Vault
  • Insert key and value to Vault
  • Lookup key from Vault
  • Data.Vault.Lazy
  • More about the implementation of Vault Vault
import qualified Data.Vault.Lazy as Vault
main = do
       let emptyVault = Vault.empty
       key <- Vault.newKey
       let newVault = Vault.insert key 2
       let maybe = Vault.lookup key newVault
       case maybe of 
            Nothing -> print "no value"
            (Just n) -> print n
       print "done"

2 Haskell maybe

  • Simplify the Maybe code
  • Given a type: Maybe Int If Maybe is Nothing return 0 else apply a funciton f to the value

    let mv = Just 3
    print $ maybe 0 (+1) (mv) -- return 4
    let mv = Nothing
    print $ maybe 0 (+1) (mv) -- return 0
    

3 Haskell Record

  • Haskell record is like a class in Java/C++ without any methods.
data MyRec = MyRec{name::String, age::Integer}
let rec = MyRec{name = "David", age=20}
print $ name rec -- "David"
print $ age rec  -- 20

  • Haskell record is just function.
data MyRec = MyRec{name::String, age::Integer}
 name::MyRec -> String
 age::MyRec -> Integer
  • This is why you can NOT have same field name even in different record. e.g.
data MyRec = MyRec{name::String, age::Integer}
data MyCatalog = MyCatalog{name:String, count::Integer}
  -- name are in MyRec and MyCatalog
  -- compiling error
  • Make record has default value
import Data.Default
data MyRec = MyRec{ name::String, age::Integer} deriving(Show)
instance Default MyRec where
        def = MyRec{name = "", age = 0}
info::MyRec
info = def MyRec{name = "David"}

4 Install all packages on your local system

  • By default install base packages
  • sudo hoogle data all will install all packages, I'm waiting now.
  • List all packages
ghc-pkg list

Author: cat

Created: 2019-08-02 Fri 14:36

Validate