Docsity

Examining Maybe and Either Types in Haskell: Algebraic Data Types, Kinds, and Typeclasses, Slides of Programming Languages

Partial preview of the text

Download Examining Maybe and Either Types in Haskell: Algebraic Data Types, Kinds, and Typeclasses and more Slides Programming Languages in PDF only on Docsity!

Reading for next class

• Learn You a Haskell

– Chapter 8

– Chapter 11

CS 252:

Advanced Programming Language Principles

Prof. Tom Austin

San José State University

Algebraic Data Types, Kinds, & Typeclasses

What happens when we run this code?

public class Maybe { public static String reverse(String s) { return new StringBuilder(s).reverse(); } public static void main(String[] args) { String rev = reverse("Racecar"); System.out.println(rev); } }

Compiler error

$ javac Maybe.java Maybe.java:3: error: incompatible types: StringBuilder cannot be converted to String return new StringBuilder(s).reverse(); ^ 1 error We needed a String but tried to return a StringBuilder.

Success!

$ javac Maybe.java $ java Maybe racecaR $ The types match, so:

1. the code compiles

2. run-time errors are

avoided

Except…

public class Maybe { public static String reverse(String s) { return ""

  • new StringBuilder(s).reverse(); } public static void main(String[] args) { String rev = reverse( null ); System.out.println(rev); } }

Null Pointer Exceptions

  • Why does Java allow^ null?
  • Can we get the same flexibility in Haskell?
  • Can we keep type safety?

The Maybe Type

  • (^) The option type
  • Used when
    • a function might not return a value
    • a caller might not pass in an argument
  • data^ Maybe^ a^ =^ Nothing | Just a

divide :: Int -> Int -> Maybe Int

divide x 0 = Nothing

divide x y = Just $ x div y

test :: Int -> Int

test d = case 1 divide d of

Just n -> n

Nothing -> error "Can't divide by zero"

main = do

putStrLn $ show $ test 9

putStrLn $ show $ test 0

import qualified Data.Map as Map

m = Map.empty

m' = Map.insert "a" 42 m

case (Map.lookup "a" m') of

Just i -> putStrLn $ show i

Nothing -> error "Key not found"

Maybe is an algebraic data type (ADT) An ADT is a composite data type; a type made up of other types. Can we create our own ADTs?

A type for trees…

data Tree = Empty | Node Tree Tree String deriving (Show)

This works for trees of

Strings, but what if we

wanted a tree of Ints?

data keyword lets us define a new type.

Types of trees

What is the type of Tree? And of Tree Int?

Trick question: types don’t have types.

So what is the type of Node?

*Main> :t Node

Node :: Tree k -> Tree k

-> k -> Tree k

Higher-order functions review

*Main> :t (++) (++) :: [a] -> [a] -> [a] ++ takes a list of a's and returns… a function that takes a list of a's and returns… a list of a's.