Dependent pattern matching lets a match on one value reveal the type or form of another. A function’s type can express the relationship first; case-splitting then refines what must be supplied in each branch. section 6.1.2 section 10.1.1
For example, StringOrInt computes a type from a Boolean: False selects String, while True selects Int. section 6.1.2
Listing 6.2. A function that calculates a type from a Bool (TypeFuns.idr)
StringOrInt : Bool -> Type StringOrInt False = String StringOrInt True = Int
The Boolean argument determines which type StringOrInt returns. section 6.1.2
Refining a return type
Start with getStringOrInt : (isInt : Bool) -> StringOrInt isInt. Before splitting isInt, the expected result type depends on its value. After splitting, the False branch expects a String and the True branch expects an Int. The branches can therefore return "Ninety four" and 94 respectively. section 6.1.2
The same relationship can determine an argument’s type. In valToString, splitting isInt tells the type checker whether y is a String or an Int, so each branch can use the appropriate conversion. section 6.1.2
valToString : (isInt : Bool) -> StringOrInt isInt -> String valToString False y = trim y valToString True y = cast y
The False branch trims a String; the True branch casts an Int to a String. section 6.1.2
A dependent type can also describe alternative forms of a value. ListLast describes a list as either empty or an initial portion followed by a final element. section 10.1.1
data ListLast : List a -> Type where Empty : ListLast [] #1 NonEmpty : (xs : List a) -> (x : a) -> ListLast (xs ++ [x]) #2
The result type of each constructor records the corresponding list form. section 10.1.1
Given input : List Int and form : ListLast input, matching form against NonEmpty xs x reveals that input must be xs ++ [x]. The list expression is permitted as a pattern because the NonEmpty pattern forces its value; an arbitrary expression cannot be used as a pattern. section 10.1.1 section 10.1.3
A with block matches an intermediate result without a separate helper. Matching listLast input introduces a pattern on the left side of the definition, allowing the match to refine the form of input. section 10.1.3
describeListEnd : List Int -> String
describeListEnd input with (listLast input)
describeListEnd [] | Empty = "Empty"
describeListEnd (xs ++ [x]) | (NonEmpty xs x)
= "Non-empty, initial portion = " ++ show xs
Matching the listLast result distinguishes an empty list from one with an initial portion and a last element. section 10.1.3
