source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
fp-lean/examples/second-lake/greeting/Main.lean | import Greeting
import Greeting.Smile
open Expression
def main : IO Unit :=
IO.println s!"Hello, {hello}, with {happy}!" |
fp-lean/examples/second-lake/greeting/Greeting.lean | def hello := "world" |
fp-lean/examples/second-lake/greeting/Greeting/Smile.lean | def Expression.happy : String := "a big smile" |
fp-lean/examples/first-lake/expected/Main.lean | import Greeting
def main : IO Unit :=
IO.println s!"Hello, {hello}!" |
fp-lean/examples/first-lake/expected/Greeting.lean | -- This module serves as the root of the `Greeting` library.
-- Import modules here that should be built as part of the library.
import Greeting.Basic |
fp-lean/examples/first-lake/expected/Greeting/Basic.lean | def hello := "world" |
fp-lean/examples/simple-hello/Hello.lean | def main : IO Unit := IO.println "Hello, world!" |
fp-lean/examples/early-return/EarlyReturn.lean | -- ANCHOR: main
def main (argv : List String) : IO UInt32 := do
let stdin ← IO.getStdin
let stdout ← IO.getStdout
let stderr ← IO.getStderr
unless argv == [] do
stderr.putStrLn s!"Expected no arguments, but got {argv.length}"
return 1
stdout.putStrLn "How would you like to be addressed?"
stdout.flush
let name := (← stdin.getLine).trim
if name == "" then
stderr.putStrLn s!"No name provided"
return 1
stdout.putStrLn s!"Hello, {name}!"
return 0
-- ANCHOR_END: main
namespace Nested
-- ANCHOR: nestedmain
def main (argv : List String) : IO UInt32 := do
let stdin ← IO.getStdin
let stdout ← IO.getStdout
let stderr ← IO.getStderr
if argv != [] then
stderr.putStrLn s!"Expected no arguments, but got {argv.length}"
pure 1
else
stdout.putStrLn "How would you like to be addressed?"
stdout.flush
let name := (← stdin.getLine).trim
if name == "" then
stderr.putStrLn s!"No name provided"
pure 1
else
stdout.putStrLn s!"Hello, {name}!"
pure 0
-- ANCHOR_END: nestedmain
end Nested
theorem mains_match : main = Nested.main := by
funext argv
simp [main, Nested.main]
congr |
fp-lean/examples/early-return/lakefile.lean | import Lake
open Lake DSL
package «earlyreturn» {
-- add package configuration options here
}
@[default_target]
lean_exe «earlyreturn» {
root := `EarlyReturn
} |
fp-lean/examples/douglib/DirTree.lean | import ExampleSupport
def String.separate := String.intercalate
-- ANCHOR: compareEntries'
def dirLT (e1 : IO.FS.DirEntry) (e2 : IO.FS.DirEntry) : Bool :=
e1.fileName < e2.fileName
-- ANCHOR_END: compareEntries'
namespace DirTree
-- ANCHOR: names
example := System.FilePath.components
-- ANCHOR_END: names
-- ANCHOR: Config
structure Config where
useASCII : Bool := false
currentPrefix : String := ""
-- ANCHOR_END: Config
-- ANCHOR: filenames
def Config.preFile (cfg : Config) :=
if cfg.useASCII then "|--" else "├──"
def Config.preDir (cfg : Config) :=
if cfg.useASCII then "| " else "│ "
def Config.fileName (cfg : Config) (file : String) : String :=
s!"{cfg.currentPrefix}{cfg.preFile} {file}"
def Config.dirName (cfg : Config) (dir : String) : String :=
s!"{cfg.currentPrefix}{cfg.preFile} {dir}/"
-- ANCHOR_END: filenames
-- ANCHOR: inDirectory
def Config.inDirectory (cfg : Config) : Config :=
{cfg with currentPrefix := cfg.preDir ++ " " ++ cfg.currentPrefix}
-- ANCHOR_END: inDirectory
-- ANCHOR: configFromArgs
def configFromArgs : List String → Option Config
| [] => some {} -- both fields default
| ["--ascii"] => some {useASCII := true}
| _ => none
-- ANCHOR_END: configFromArgs
-- ANCHOR: usage
def usage : String :=
"Usage: doug [--ascii]
Options:
\t--ascii\tUse ASCII characters to display the directory structure"
-- ANCHOR_END: usage
-- ANCHOR: Entry
inductive Entry where
| file : String → Entry
| dir : String → Entry
-- ANCHOR_END: Entry
-- ANCHOR: toEntry
def toEntry (path : System.FilePath) : IO (Option Entry) := do
match path.components.getLast? with
| none => pure (some (.dir ""))
| some "." | some ".." => pure none
| some name =>
pure (some (if (← path.isDir) then .dir name else .file name))
-- ANCHOR_END: toEntry
-- ANCHOR: doList
def doList [Applicative f] : List α → (α → f Unit) → f Unit
| [], _ => pure ()
| x :: xs, action =>
action x *>
doList xs action
-- ANCHOR_END: doList
namespace Old
-- ANCHOR: OldShowFile
def showFileName (cfg : Config) (file : String) : IO Unit := do
IO.println (cfg.fileName file)
def showDirName (cfg : Config) (dir : String) : IO Unit := do
IO.println (cfg.dirName dir)
-- ANCHOR_END: OldShowFile
-- ANCHOR: OldDirTree
partial def dirTree (cfg : Config) (path : System.FilePath) : IO Unit := do
match ← toEntry path with
| none => pure ()
| some (.file name) => showFileName cfg name
| some (.dir name) =>
showDirName cfg name
let contents ← path.readDir
let newConfig := cfg.inDirectory
doList (contents.qsort dirLT).toList fun d =>
dirTree newConfig d.path
-- ANCHOR_END: OldDirTree
-- ANCHOR: OldMain
def main (args : List String) : IO UInt32 := do
match configFromArgs args with
| some config =>
dirTree config (← IO.currentDir)
pure 0
| none =>
IO.eprintln s!"Didn't understand argument(s) {" ".separate args}\n"
IO.eprintln usage
pure 1
-- ANCHOR_END: OldMain
-- #eval main ["--ascii"]
end Old
namespace Readerish
-- ANCHOR: ConfigIO
def ConfigIO (α : Type) : Type :=
Config → IO α
instance : Monad ConfigIO where
pure x := fun _ => pure x
bind result next := fun cfg => do
let v ← result cfg
next v cfg
-- ANCHOR_END: ConfigIO
-- ANCHOR: ConfigIORun
def ConfigIO.run (action : ConfigIO α) (cfg : Config) : IO α :=
action cfg
-- ANCHOR_END: ConfigIORun
-- ANCHOR: currentConfig
def currentConfig : ConfigIO Config :=
fun cfg => pure cfg
-- ANCHOR_END: currentConfig
-- ANCHOR: locally
def locally (change : Config → Config) (action : ConfigIO α) : ConfigIO α :=
fun cfg => action (change cfg)
-- ANCHOR_END: locally
-- ANCHOR: runIO
def runIO (action : IO α) : ConfigIO α :=
fun _ => action
-- ANCHOR_END: runIO
-- ANCHOR: MedShowFileDir
def showFileName (file : String) : ConfigIO Unit := do
runIO (IO.println ((← currentConfig).fileName file))
def showDirName (dir : String) : ConfigIO Unit := do
runIO (IO.println ((← currentConfig).dirName dir))
-- ANCHOR_END: MedShowFileDir
-- ANCHOR: MedDirTree
partial def dirTree (path : System.FilePath) : ConfigIO Unit := do
match ← runIO (toEntry path) with
| none => pure ()
| some (.file name) => showFileName name
| some (.dir name) =>
showDirName name
let contents ← runIO path.readDir
locally (·.inDirectory)
(doList (contents.qsort dirLT).toList fun d =>
dirTree d.path)
-- ANCHOR_END: MedDirTree
-- ANCHOR: MedMain
def main (args : List String) : IO UInt32 := do
match configFromArgs args with
| some config =>
(dirTree (← IO.currentDir)).run config
pure 0
| none =>
IO.eprintln s!"Didn't understand argument(s) {" ".separate args}\n"
IO.eprintln usage
pure 1
-- ANCHOR_END: MedMain
end Readerish
namespace MyMonadLift
-- ANCHOR: MyMonadLift
class MonadLift (m : Type u → Type v) (n : Type u → Type w) where
monadLift : {α : Type u} → m α → n α
-- ANCHOR_END: MyMonadLift
end MyMonadLift
similar datatypes DirTree.MyMonadLift.MonadLift MonadLift
namespace T
-- These are replicated here to make sure we don't forget any important declarations
-- ANCHOR: MyReaderT
def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) :
Type (max u v) :=
ρ → m α
-- ANCHOR_END: MyReaderT
-- ANCHOR: MonadMyReaderT
instance [Monad m] : Monad (ReaderT ρ m) where
pure x := fun _ => pure x
bind result next := fun env => do
let v ← result env
next v env
-- ANCHOR_END: MonadMyReaderT
namespace R
-- ANCHOR: MyReaderTread
def read [Monad m] : ReaderT ρ m ρ :=
fun env => pure env
-- ANCHOR_END: MyReaderTread
end R
-- ANCHOR: MonadReader
class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) :
Type (max (u + 1) v) where
read : m ρ
instance [Monad m] : MonadReader ρ (ReaderT ρ m) where
read := fun env => pure env
export MonadReader (read)
-- ANCHOR_END: MonadReader
-- ANCHOR: ReaderTConfigIO
abbrev ConfigIO (α : Type) : Type := ReaderT Config IO α
-- ANCHOR_END: ReaderTConfigIO
-- ANCHOR: MonadLiftReaderT
instance : MonadLift m (ReaderT ρ m) where
monadLift action := fun _ => action
-- ANCHOR_END: MonadLiftReaderT
-- ANCHOR: showFileAndDir
def showFileName (file : String) : ConfigIO Unit := do
IO.println s!"{(← read).currentPrefix} {file}"
def showDirName (dir : String) : ConfigIO Unit := do
IO.println s!"{(← read).currentPrefix} {dir}/"
-- ANCHOR_END: showFileAndDir
-- ANCHOR: MyMonadWithReader
class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where
withReader {α : Type u} : (ρ → ρ) → m α → m α
-- ANCHOR_END: MyMonadWithReader
-- ANCHOR: exportWithReader
export MonadWithReader (withReader)
-- ANCHOR_END: exportWithReader
-- ANCHOR: ReaderTWithReader
instance : MonadWithReader ρ (ReaderT ρ m) where
withReader change action :=
fun cfg => action (change cfg)
-- ANCHOR_END: ReaderTWithReader
-- ANCHOR: readerTDirTree
partial def dirTree (path : System.FilePath) : ConfigIO Unit := do
match ← toEntry path with
| none => pure ()
| some (.file name) => showFileName name
| some (.dir name) =>
showDirName name
let contents ← path.readDir
withReader (·.inDirectory)
(doList (contents.qsort dirLT).toList fun d =>
dirTree d.path)
-- ANCHOR_END: readerTDirTree
-- ANCHOR: NewMain
def main (args : List String) : IO UInt32 := do
match configFromArgs args with
| some config =>
dirTree (← IO.currentDir) config
pure 0
| none =>
IO.eprintln s!"Didn't understand argument(s) {" ".separate args}\n"
IO.eprintln usage
pure 1
-- ANCHOR_END: NewMain
end T
end DirTree
similar datatypes DirTree.T.MonadWithReader MonadWithReader |
fp-lean/examples/Examples/Intro.lean | import ExampleSupport
import SubVerso.Examples
set_option linter.unusedVariables false
-- ANCHOR: three
example : (
1 + 2
) = (
3
) := rfl
-- ANCHOR_END: three
/-- info: 3 -/
#check_msgs in
-- ANCHOR: threeEval
#eval 1 + 2
-- ANCHOR_END: threeEval
/-- info: 11 -/
#check_msgs in
-- ANCHOR: orderOfOperations
#eval 1 + 2 * 5
-- ANCHOR_END: orderOfOperations
/-- info: 15 -/
#check_msgs in
-- ANCHOR: orderOfOperationsWrong
#eval (1 + 2) * 5
-- ANCHOR_END: orderOfOperationsWrong
/-- info: "Hello, Lean!" -/
#check_msgs in
--- ANCHOR: stringAppendHello
#eval String.append "Hello, " "Lean!"
--- ANCHOR_END: stringAppendHello
/-- info: "great oak tree" -/
#check_msgs in
--- ANCHOR: stringAppendNested
#eval String.append "great " (String.append "oak " "tree")
--- ANCHOR_END: stringAppendNested
evaluation steps {{{ stringAppend }}}
-- ANCHOR: stringAppend
String.append "it is " (if 1 > 2 then "yes" else "no")
===>
String.append "it is " (if false then "yes" else "no")
===>
String.append "it is " "no"
===>
"it is no"
-- ANCHOR_END: stringAppend
end evaluation steps
/--
error: could not synthesize a `ToExpr`, `Repr`, or `ToString` instance for type
String → String
-/
#check_msgs in
-- ANCHOR: stringAppendReprFunction
#eval String.append "it is "
-- ANCHOR_END: stringAppendReprFunction
/-- info:
false
-/
#check_msgs in
-- ANCHOR: stringAppendCond
#eval 1 > 2
-- ANCHOR_END: stringAppendCond
/-- info:
3
-/
#check_msgs in
-- ANCHOR: onePlusTwoEval
#eval (1 + 2 : Nat)
-- ANCHOR_END: onePlusTwoEval
-- ANCHOR: onePlusTwoType
example : (
(1 + 2 : Nat)
) = (
3
) := rfl
-- ANCHOR_END: onePlusTwoType
-- ANCHOR: oneMinusTwo
example : (
1 - 2
) = (
0
) := rfl
-- ANCHOR_END: oneMinusTwo
/-- info:
0
-/
#check_msgs in
-- ANCHOR: oneMinusTwoEval
#eval (1 - 2 : Nat)
-- ANCHOR_END: oneMinusTwoEval
-- ANCHOR: oneMinusTwoInt
example : (
(1 - 2 : Int)
) = (
-1
) := rfl
-- ANCHOR_END: oneMinusTwoInt
/-- info:
-1
-/
#check_msgs in
-- ANCHOR: oneMinusTwoIntEval
#eval (1 - 2 : Int)
-- ANCHOR_END: oneMinusTwoIntEval
/-- info:
1 - 2 : Int
-/
#check_msgs in
-- ANCHOR: oneMinusTwoIntType
#check (1 - 2 : Int)
-- ANCHOR_END: oneMinusTwoIntType
/--
error: Application type mismatch: The argument
["hello", " "]
has type
List String
but is expected to have type
String
in the application
String.append ["hello", " "]
---
info: sorry.append "world" : String
-/
#check_msgs in
-- ANCHOR: stringAppendList
#check String.append ["hello", " "] "world"
-- ANCHOR_END: stringAppendList
-- ANCHOR: hello
def hello := "Hello"
-- ANCHOR_END: hello
-- ANCHOR: helloNameVal
example : (
hello
) = (
"Hello"
) := rfl
-- ANCHOR_END: helloNameVal
-- ANCHOR: lean
def lean : String := "Lean"
-- ANCHOR_END: lean
/-- info:
"Hello Lean"
-/
#check_msgs in
-- ANCHOR: helloLean
#eval String.append hello (String.append " " lean)
-- ANCHOR_END: helloLean
-- ANCHOR: add1
def add1 (n : Nat) : Nat := n + 1
-- ANCHOR_END: add1
/-- info:
add1 (n : Nat) : Nat
-/
#check_msgs in
-- ANCHOR: add1sig
#check add1
-- ANCHOR_END: add1sig
/-- info:
add1 : Nat → Nat
-/
#check_msgs in
-- ANCHOR: add1type
#check (add1)
-- ANCHOR_END: add1type
-- ANCHOR: add1typeASCII
example : Nat -> Nat := add1
-- ANCHOR_END: add1typeASCII
/-- info:
8
-/
#check_msgs in
-- ANCHOR: add1_7
#eval add1 7
-- ANCHOR_END: add1_7
/--
error: Application type mismatch: The argument
"seven"
has type
String
but is expected to have type
Nat
in the application
add1 "seven"
---
info: add1 sorry : Nat
-/
#check_msgs in
-- ANCHOR: add1_string
#check add1 "seven"
-- ANCHOR_END: add1_string
/-- warning: declaration uses 'sorry' -/
#check_msgs in
-- ANCHOR: add1_warn
def foo := add1 sorry
-- ANCHOR_END: add1_warn
section
open SubVerso.Examples
-- ANCHOR: maximum
def maximum (n : Nat) (k : Nat) : Nat :=
if n < k then
k
else n
-- ANCHOR_END: maximum
end
-- ANCHOR: spaceBetween
def spaceBetween (before : String) (after : String) : String :=
String.append before (String.append " " after)
-- ANCHOR_END: spaceBetween
/-- info:
maximum : Nat → Nat → Nat
-/
#check_msgs in
-- ANCHOR: maximumType
#check (maximum)
-- ANCHOR_END: maximumType
-- ANCHOR: maximumTypeASCII
example : Nat -> Nat -> Nat := maximum
-- ANCHOR_END: maximumTypeASCII
/-- info:
maximum 3 : Nat → Nat
-/
#check_msgs in
-- ANCHOR: maximum3Type
#check maximum 3
-- ANCHOR_END: maximum3Type
/-- info:
spaceBetween "Hello " : String → String
-/
#check_msgs in
-- ANCHOR: stringAppendHelloType
#check spaceBetween "Hello "
-- ANCHOR_END: stringAppendHelloType
-- ANCHOR: currying
example : (
Nat → Nat → Nat
) = (
Nat → (Nat → Nat)
) := rfl
-- ANCHOR_END: currying
evaluation steps {{{ maximum_eval }}}
-- ANCHOR: maximum_eval
maximum (5 + 8) (2 * 7)
===>
maximum 13 14
===>
if 13 < 14 then 14 else 13
===>
14
-- ANCHOR_END: maximum_eval
end evaluation steps
---ANCHOR: joinStringsWith
def joinStringsWith (sep x y : String) : String := String.append x (String.append sep y)
example : String → String → String → String := joinStringsWith
example : String → String → String := joinStringsWith ": "
---ANCHOR_END: joinStringsWith
section
open SubVerso.Examples
%show_name joinStringsWith as joinStringsWith.name
%show_term joinStringsWith.type := String → String → String → String
end
open SubVerso.Examples in
-- ANCHOR: volume
def volume : Nat → Nat → Nat → Nat :=
fun x y z => x * y * z
-- ANCHOR_END: volume
open SubVerso.Examples in
%show_name volume as volume.name
evaluation steps {{{ joinStringsWithEx }}}
-- ANCHOR: joinStringsWithEx
joinStringsWith ", " "one" "and another"
===>
"one, and another"
-- ANCHOR_END: joinStringsWithEx
end evaluation steps
-- ANCHOR: StringTypeDef
def Str : Type := String
-- ANCHOR_END: StringTypeDef
open SubVerso.Examples in
%show_name Str as Str.name
-- ANCHOR: aStr
def aStr : Str := "This is a string."
-- ANCHOR_END: aStr
-- ANCHOR: NaturalNumberTypeDef
def NaturalNumber : Type := Nat
-- ANCHOR_END: NaturalNumberTypeDef
open SubVerso.Examples in
%show_name NaturalNumber
discarding
open SubVerso.Examples in
/--
error: failed to synthesize
OfNat NaturalNumber 38
numerals are polymorphic in Lean, but the numeral `38` cannot be used in a context where the expected type is
NaturalNumber
due to the absence of the instance above
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: thirtyEight
def thirtyEight : NaturalNumber := 38
-- ANCHOR_END: thirtyEight
stop discarding
open SubVerso.Examples in
-- ANCHOR: thirtyEightFixed
def thirtyEight : NaturalNumber := (38 : Nat)
-- ANCHOR_END: thirtyEightFixed
-- ANCHOR: NTypeDef
abbrev N : Type := Nat
-- ANCHOR_END: NTypeDef
-- ANCHOR: thirtyNine
def thirtyNine : N := 39
-- ANCHOR_END: thirtyNine
evaluation steps {{{ NaturalNumberDef }}}
-- ANCHOR: NaturalNumberDef
NaturalNumber
===>
Nat
-- ANCHOR_END: NaturalNumberDef
end evaluation steps
/-- info:
1.2 : Float
-/
#check_msgs in
-- ANCHOR: onePointTwo
#check 1.2
-- ANCHOR_END: onePointTwo
/-- info:
-454.2123215 : Float
-/
#check_msgs in
-- ANCHOR: negativeLots
#check -454.2123215
-- ANCHOR_END: negativeLots
/-- info:
0.0 : Float
-/
#check_msgs in
-- ANCHOR: zeroPointZero
#check 0.0
-- ANCHOR_END: zeroPointZero
/-- info:
0 : Nat
-/
#check_msgs in
-- ANCHOR: zeroNat
#check 0
-- ANCHOR_END: zeroNat
/-- info:
0 : Float
-/
#check_msgs in
-- ANCHOR: zeroFloat
#check (0 : Float)
-- ANCHOR_END: zeroFloat
-- ANCHOR: Point
structure Point where
x : Float
y : Float
-- ANCHOR_END: Point
section
open SubVerso.Examples
%show_name Point as Point.name
%show_name Repr as Repr.name
open Point
%show_name x as Point.x
%show_name y as Point.y
end
-- ANCHOR: origin
def origin : Point := { x := 0.0, y := 0.0 }
-- ANCHOR_END: origin
/-- info:
{ x := 0.000000, y := 0.000000 }
-/
#check_msgs in
-- ANCHOR: originEval
#eval origin
-- ANCHOR_END: originEval
namespace Oops
structure Point where
x : Float
y : Float
-- ANCHOR: originNoRepr
def origin : Point := { x := 0.0, y := 0.0 }
-- ANCHOR_END: originNoRepr
open SubVerso.Examples in
%show_name origin as origin.name
end Oops
/-- error:
invalid {...} notation, expected type is not known
-/
#check_msgs in
-- ANCHOR: originNoType
#check { x := 0.0, y := 0.0 }
-- ANCHOR_END: originNoType
/-- info:
{ x := 0.0, y := 0.0 } : Point
-/
#check_msgs in
-- ANCHOR: originWithAnnot
#check ({ x := 0.0, y := 0.0 } : Point)
-- ANCHOR_END: originWithAnnot
/-- info:
{ x := 0.0, y := 0.0 } : Point
-/
#check_msgs in
-- ANCHOR: originWithAnnot2
#check { x := 0.0, y := 0.0 : Point}
-- ANCHOR_END: originWithAnnot2
namespace Oops
-- ANCHOR: zeroXBad
def zeroX (p : Point) : Point :=
{ x := 0, y := p.y }
-- ANCHOR_END: zeroXBad
end Oops
-- ANCHOR: zeroX
def zeroX (p : Point) : Point :=
{ p with x := 0 }
-- ANCHOR_END: zeroX
open SubVerso.Examples in
%show_name zeroX as zeroX.name
open SubVerso.Examples in
%show_term zeroPointZero.term := 0.0
-- ANCHOR: fourAndThree
def fourAndThree : Point :=
{ x := 4.3, y := 3.4 }
-- ANCHOR_END: fourAndThree
/-- info:
{ x := 4.300000, y := 3.400000 }
-/
#check_msgs in
-- ANCHOR: fourAndThreeEval
#eval fourAndThree
-- ANCHOR_END: fourAndThreeEval
/-- info:
{ x := 0.000000, y := 3.400000 }
-/
#check_msgs in
-- ANCHOR: zeroXFourAndThreeEval
#eval zeroX fourAndThree
-- ANCHOR_END: zeroXFourAndThreeEval
/-- info:
Point.mk : Float → Float → Point
-/
#check_msgs in
-- ANCHOR: Pointmk
#check (Point.mk)
-- ANCHOR_END: Pointmk
/-- info:
Point.x : Point → Float
-/
#check_msgs in
-- ANCHOR: Pointx
#check (Point.x)
-- ANCHOR_END: Pointx
/-- info:
Point.y : Point → Float
-/
#check_msgs in
-- ANCHOR: Pointy
#check (Point.y)
-- ANCHOR_END: Pointy
/-- info:
0.000000
-/
#check_msgs in
-- ANCHOR: originx1
#eval Point.x origin
-- ANCHOR_END: originx1
/-- info:
0.000000
-/
#check_msgs in
-- ANCHOR: originx
#eval origin.x
-- ANCHOR_END: originx
/-- info:
0.000000
-/
#check_msgs in
-- ANCHOR: originy
#eval origin.y
-- ANCHOR_END: originy
open SubVerso.Examples in
-- ANCHOR: addPoints
def addPoints (p1 : Point) (p2 : Point) : Point :=
{ x := p1.x + p2.x, y := p1.y + p2.y }
-- ANCHOR_END: addPoints
/-- info:
{ x := -6.500000, y := 32.200000 }
-/
#check_msgs in
-- ANCHOR: addPointsEx
#eval addPoints { x := 1.5, y := 32 } { x := -8, y := 0.2 }
-- ANCHOR_END: addPointsEx
-- ANCHOR: Point3D
structure Point3D where
x : Float
y : Float
z : Float
-- ANCHOR_END: Point3D
-- ANCHOR: origin3D
def origin3D : Point3D := { x := 0.0, y := 0.0, z := 0.0 }
-- ANCHOR_END: origin3D
namespace Ctor
-- ANCHOR: PointCtorName
structure Point where
point ::
x : Float
y : Float
-- ANCHOR_END: PointCtorName
-- ANCHOR: PointCtorNameName
example := Point.point
-- ANCHOR_END: PointCtorNameName
end Ctor
section
open SubVerso.Examples
open Ctor
%show_name Point.point
end
/-- info:
{ x := 1.5, y := 2.8 } : Point
-/
#check_msgs in
-- ANCHOR: checkPointMk
#check Point.mk 1.5 2.8
-- ANCHOR_END: checkPointMk
/-- info:
"one string and another"
-/
#check_msgs in
-- ANCHOR: stringAppendDot
#eval "one string".append " and another"
-- ANCHOR_END: stringAppendDot
-- ANCHOR: modifyBoth
def Point.modifyBoth (f : Float → Float) (p : Point) : Point :=
{ x := f p.x, y := f p.y }
-- ANCHOR_END: modifyBoth
section
open SubVerso.Examples
%show_name Point.modifyBoth
open Point
%show_name modifyBoth as modifyBoth.name
end
/-- info:
{ x := 4.000000, y := 3.000000 }
-/
#check_msgs in
-- ANCHOR: modifyBothTest
#eval fourAndThree.modifyBoth Float.floor
-- ANCHOR_END: modifyBothTest
open SubVerso.Examples in
%show_name Float.floor
-- ANCHOR: distance
def distance (p1 : Point) (p2 : Point) : Float :=
Float.sqrt (((p2.x - p1.x) ^ 2.0) + ((p2.y - p1.y) ^ 2.0))
-- ANCHOR_END: distance
/-- info:
5.000000
-/
#check_msgs in
-- ANCHOR: evalDistance
#eval distance { x := 1.0, y := 2.0 } { x := 5.0, y := -1.0 }
-- ANCHOR_END: evalDistance
-- ANCHOR: Hamster
structure Hamster where
name : String
fluffy : Bool
-- ANCHOR_END: Hamster
-- ANCHOR: Book
structure Book where
makeBook ::
title : String
author : String
price : Float
-- ANCHOR_END: Book
set_option SubVerso.examples.suppressedNamespaces "Inductive Oops Ooops Oooops _root_ BetterPlicity StdLibNoUni BadUnzip NRT WithPattern MatchDef AutoImpl"
namespace Inductive
-- ANCHOR: Bool
inductive Bool where
| false : Bool
| true : Bool
-- ANCHOR_END: Bool
attribute [inherit_doc _root_.Bool] Inductive.Bool
attribute [inherit_doc _root_.Bool.true] Inductive.Bool.true
attribute [inherit_doc _root_.Bool.false] Inductive.Bool.false
section
-- ANCHOR: BoolNames
example : List Bool := [Bool.true, Bool.false]
open Bool
example : List Bool := [true, false]
-- ANCHOR_END: BoolNames
end
-- ANCHOR: Nat
inductive Nat where
| zero : Nat
| succ (n : Nat) : Nat
-- ANCHOR_END: Nat
attribute [inherit_doc _root_.Nat] Inductive.Nat
attribute [inherit_doc _root_.Nat.zero] Inductive.Nat.zero
attribute [inherit_doc _root_.Nat.succ] Inductive.Nat.succ
section
-- ANCHOR: NatNames
example : Nat := Nat.succ Nat.zero
open Nat
example : Nat := succ zero
-- ANCHOR_END: NatNames
end
open Nat
open SubVerso.Examples
%show_name Nat as fakeNat
%show_name Bool as fakeBool
section
open Inductive.Bool
%show_term fakeTrue : Inductive.Bool := true
%show_term fakeFalse : Inductive.Bool := false
end
%show_name Bool.true as fakeBool.true
%show_name Bool.false as fakeBool.false
%show_name zero as fakeZero
%show_name succ as fakeSucc
%show_name Nat.zero as Nat.fakeZero
%show_name Nat.succ as Nat.fakeSucc
instance : OfNat Inductive.Nat n where
ofNat := go n
where
go
| .zero => .zero
| .succ k => .succ (go k)
evaluation steps : Nat {{{ four }}}
-- ANCHOR: four
Nat.succ (Nat.succ (Nat.succ (Nat.succ Nat.zero)))
===>
4
-- ANCHOR_END: four
end evaluation steps
end Inductive
open SubVerso.Examples in
-- ANCHOR: isZero
def isZero (n : Nat) : Bool :=
match n with
| Nat.zero => true
| Nat.succ k => false
-- ANCHOR_END: isZero
evaluation steps {{{ isZeroZeroSteps }}}
-- ANCHOR: isZeroZeroSteps
isZero Nat.zero
===>
match Nat.zero with
| Nat.zero => true
| Nat.succ k => false
===>
true
-- ANCHOR_END: isZeroZeroSteps
end evaluation steps
/-- info:
true
-/
#check_msgs in
-- ANCHOR: isZeroZero
#eval isZero 0
-- ANCHOR_END: isZeroZero
evaluation steps {{{ isZeroFiveSteps }}}
-- ANCHOR: isZeroFiveSteps
isZero 5
===>
isZero (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ Nat.zero)))))
===>
match Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ Nat.zero)))) with
| Nat.zero => true
| Nat.succ k => false
===>
false
-- ANCHOR_END: isZeroFiveSteps
end evaluation steps
/-- info:
false
-/
#check_msgs in
-- ANCHOR: isZeroFive
#eval isZero 5
-- ANCHOR_END: isZeroFive
open SubVerso.Examples in
-- ANCHOR: pred
def pred (n : Nat) : Nat :=
match n with
| Nat.zero => Nat.zero
| Nat.succ k => k
-- ANCHOR_END: pred
open SubVerso.Examples in
%show_name pred as pred.name
/-- info:
4
-/
#check_msgs in
-- ANCHOR: predFive
#eval pred 5
-- ANCHOR_END: predFive
evaluation steps {{{ predFiveSteps }}}
-- ANCHOR: predFiveSteps
pred 5
===>
pred (Nat.succ 4)
===>
match Nat.succ 4 with
| Nat.zero => Nat.zero
| Nat.succ k => k
===>
4
-- ANCHOR_END: predFiveSteps
end evaluation steps
/-- info:
838
-/
#check_msgs in
-- ANCHOR: predBig
#eval pred 839
-- ANCHOR_END: predBig
/-- info:
0
-/
#check_msgs in
-- ANCHOR: predZero
#eval pred 0
-- ANCHOR_END: predZero
-- ANCHOR: depth
def depth (p : Point3D) : Float :=
match p with
| { x:= h, y := w, z := d } => d
-- ANCHOR_END: depth
open SubVerso.Examples in
-- ANCHOR: even
def even (n : Nat) : Bool :=
match n with
| Nat.zero => true
| Nat.succ k => not (even k)
-- ANCHOR_END: even
/-- info:
true
-/
#check_msgs in
-- ANCHOR: _something
#eval even 2
-- ANCHOR_END: _something
/-- info:
false
-/
#check_msgs in
-- ANCHOR: _something_more
#eval even 5
-- ANCHOR_END: _something_more
/--
error: fail to show termination for
evenLoops
with errors
failed to infer structural recursion:
Not considering parameter n of evenLoops:
it is unchanged in the recursive calls
no parameters suitable for structural recursion
well-founded recursion cannot be used, `evenLoops` does not take any (non-fixed) arguments
-/
#check_msgs in
-- ANCHOR: evenLoops
def evenLoops (n : Nat) : Bool :=
match n with
| Nat.zero => true
| Nat.succ k => not (evenLoops n)
-- ANCHOR_END: evenLoops
open SubVerso.Examples in
-- ANCHOR: plus
def plus (n : Nat) (k : Nat) : Nat :=
match k with
| Nat.zero => n
| Nat.succ k' => Nat.succ (plus n k')
-- ANCHOR_END: plus
open SubVerso.Examples in
%show_name plus as plus.name
evaluation steps {{{ plusThreeTwo }}}
-- ANCHOR: plusThreeTwo
plus 3 2
===>
plus 3 (Nat.succ (Nat.succ Nat.zero))
===>
match Nat.succ (Nat.succ Nat.zero) with
| Nat.zero => 3
| Nat.succ k' => Nat.succ (plus 3 k')
===>
Nat.succ (plus 3 (Nat.succ Nat.zero))
===>
Nat.succ (match Nat.succ Nat.zero with
| Nat.zero => 3
| Nat.succ k' => Nat.succ (plus 3 k'))
===>
Nat.succ (Nat.succ (plus 3 Nat.zero))
===>
Nat.succ (Nat.succ (match Nat.zero with
| Nat.zero => 3
| Nat.succ k' => Nat.succ (plus 3 k')))
===>
Nat.succ (Nat.succ 3)
===>
5
-- ANCHOR_END: plusThreeTwo
end evaluation steps
-- ANCHOR: times
def times (n : Nat) (k : Nat) : Nat :=
match k with
| Nat.zero => Nat.zero
| Nat.succ k' => plus n (times n k')
-- ANCHOR_END: times
#eval times 5 3
-- ANCHOR: minus
def minus (n : Nat) (k : Nat) : Nat :=
match k with
| Nat.zero => n
| Nat.succ k' => pred (minus n k')
-- ANCHOR_END: minus
open SubVerso.Examples in
/--
error: fail to show termination for
div
with errors
failed to infer structural recursion:
Not considering parameter k of div:
it is unchanged in the recursive calls
Cannot use parameter k:
failed to eliminate recursive application
div (n - k) k
failed to prove termination, possible solutions:
- Use `have`-expressions to prove the remaining goals
- Use `termination_by` to specify a different well-founded relation
- Use `decreasing_by` to specify your own tactic for discharging this kind of goal
k n : Nat
h✝ : ¬n < k
⊢ n - k < n
-/
#check_msgs in
-- ANCHOR: div
def div (n : Nat) (k : Nat) : Nat :=
if n < k then
0
else Nat.succ (div (n - k) k)
-- ANCHOR_END: div
open SubVerso.Examples in
-- ANCHOR: PPoint
structure PPoint (α : Type) where
x : α
y : α
-- ANCHOR_END: PPoint
section
open SubVerso.Examples
%show_name PPoint as PPoint.name
open PPoint
%show_name x as PPoint.x
%show_name y as PPoint.y
end
-- ANCHOR: natPoint
def natOrigin : PPoint Nat :=
{ x := Nat.zero, y := Nat.zero }
-- ANCHOR_END: natPoint
section
open SubVerso.Examples
%show_name natOrigin as natOrigin.name
end
-- ANCHOR: toPPoint
def Point.toPPoint (p : Point) : PPoint Float :=
{ x := p.x, y := p.y }
-- ANCHOR_END: toPPoint
open SubVerso.Examples in
-- ANCHOR: replaceX
def replaceX (α : Type) (point : PPoint α) (newX : α) : PPoint α :=
{ point with x := newX }
-- ANCHOR_END: replaceX
/-- info:
replaceX : (α : Type) → PPoint α → α → PPoint α
-/
#check_msgs in
-- ANCHOR: replaceXT
#check (replaceX)
-- ANCHOR_END: replaceXT
open SubVerso.Examples in
/-- info:
replaceX Nat : PPoint Nat → Nat → PPoint Nat
-/
#check_msgs in
-- ANCHOR: replaceXNatT
#check replaceX Nat
-- ANCHOR_END: replaceXNatT
/-- info:
replaceX Nat natOrigin : Nat → PPoint Nat
-/
#check_msgs in
-- ANCHOR: replaceXNatOriginT
#check replaceX Nat natOrigin
-- ANCHOR_END: replaceXNatOriginT
/-- info:
replaceX Nat natOrigin 5 : PPoint Nat
-/
#check_msgs in
-- ANCHOR: replaceXNatOriginFiveT
#check replaceX Nat natOrigin 5
-- ANCHOR_END: replaceXNatOriginFiveT
/-- info:
{ x := 5, y := 0 }
-/
#check_msgs in
-- ANCHOR: replaceXNatOriginFiveV
#eval replaceX Nat natOrigin 5
-- ANCHOR_END: replaceXNatOriginFiveV
-- ANCHOR: primesUnder10
def primesUnder10 : List Nat := [2, 3, 5, 7]
-- ANCHOR_END: primesUnder10
open SubVerso.Examples in
%show_name primesUnder10 as primesUnder10.name
namespace Oops
open SubVerso.Examples
-- ANCHOR: List
inductive List (α : Type) where
| nil : List α
| cons : α → List α → List α
-- ANCHOR_END: List
%show_term fakeList : Type → Type := List
open List
%show_term fakeNil : {α : Type} → Oops.List α := nil
%show_term fakeCons : {α : Type} → α → Oops.List α → Oops.List α := cons
end Oops
similar datatypes List Oops.List
-- ANCHOR: explicitPrimesUnder10
def explicitPrimesUnder10 : List Nat :=
List.cons 2 (List.cons 3 (List.cons 5 (List.cons 7 List.nil)))
-- ANCHOR_END: explicitPrimesUnder10
open SubVerso.Examples in
%show_name explicitPrimesUnder10 as explicitPrimesUnder10.name
namespace Ooops
open SubVerso.Examples
-- ANCHOR: length1
def length (α : Type) (xs : List α) : Nat :=
match xs with
| List.nil => Nat.zero
| List.cons y ys => Nat.succ (length α ys)
-- ANCHOR_END: length1
evaluation steps {{{ length1EvalSummary }}}
-- ANCHOR: length1EvalSummary
length String ["Sourdough", "bread"]
===>
length String (List.cons "Sourdough" (List.cons "bread" List.nil))
===>
Nat.succ (length String (List.cons "bread" List.nil))
===>
Nat.succ (Nat.succ (length String List.nil))
===>
Nat.succ (Nat.succ Nat.zero)
===>
2
-- ANCHOR_END: length1EvalSummary
end evaluation steps
evaluation steps {{{ length1Eval }}}
-- ANCHOR: length1Eval
length String ["Sourdough", "bread"]
===>
length String (List.cons "Sourdough" (List.cons "bread" List.nil))
===>
match List.cons "Sourdough" (List.cons "bread" List.nil) with
| List.nil => Nat.zero
| List.cons y ys => Nat.succ (length String ys)
===>
Nat.succ (length String (List.cons "bread" List.nil))
===>
Nat.succ (match List.cons "bread" List.nil with
| List.nil => Nat.zero
| List.cons y ys => Nat.succ (length String ys))
===>
Nat.succ (Nat.succ (length String List.nil))
===>
Nat.succ (Nat.succ (match List.nil with
| List.nil => Nat.zero
| List.cons y ys => Nat.succ (length String ys)))
===>
Nat.succ (Nat.succ Nat.zero)
===>
2
-- ANCHOR_END: length1Eval
end evaluation steps
end Ooops
namespace Oooops
-- ANCHOR: length2
def length (α : Type) (xs : List α) : Nat :=
match xs with
| [] => 0
| y :: ys => Nat.succ (length α ys)
-- ANCHOR_END: length2
end Oooops
namespace BetterPlicity
open SubVerso.Examples
-- ANCHOR: replaceXImp
def replaceX {α : Type} (point : PPoint α) (newX : α) : PPoint α :=
{ point with x := newX }
-- ANCHOR_END: replaceXImp
/-- info:
{ x := 5, y := 0 }
-/
#check_msgs in
-- ANCHOR: replaceXImpNat
#eval replaceX natOrigin 5
-- ANCHOR_END: replaceXImpNat
-- ANCHOR: lengthImp
def length {α : Type} (xs : List α) : Nat :=
match xs with
| [] => 0
| y :: ys => Nat.succ (length ys)
-- ANCHOR_END: lengthImp
/-- info:
4
-/
#check_msgs in
-- ANCHOR: lengthImpPrimes
#eval length primesUnder10
-- ANCHOR_END: lengthImpPrimes
end BetterPlicity
/-- info:
4
-/
#check_msgs in
-- ANCHOR: lengthDotPrimes
#eval primesUnder10.length
-- ANCHOR_END: lengthDotPrimes
/-- info:
List.length : List Int → Nat
-/
#check_msgs in
-- ANCHOR: lengthExpNat
#check List.length (α := Int)
-- ANCHOR_END: lengthExpNat
def x := Unit
structure Iso (α : Type u) (β : Type u) : Type u where
into : α → β
outOf : β → α
comp1 : into ∘ outOf = id
comp2 : outOf ∘ into = id
-- Standard library copies without universe parameters
namespace StdLibNoUni
open SubVerso.Examples
-- ANCHOR: Option
inductive Option (α : Type) : Type where
| none : Option α
| some (val : α) : Option α
-- ANCHOR_END: Option
%show_name Option as fakeOption
%show_name Option.none as fakeOption.none
%show_name Option.some as fakeOption.some
namespace Option
%show_name none as fakeNone
%show_name some as fakeSome
end Option
-- ANCHOR: Prod
structure Prod (α : Type) (β : Type) : Type where
fst : α
snd : β
-- ANCHOR_END: Prod
%show_name Prod as fakeProd
%show_name Prod.fst as fakeProd.fst
%show_name Prod.snd as fakeProd.snd
namespace Prod
%show_name fst as fakeFst
%show_name snd as fakeSnd
end Prod
-- Justify the claim in the text that Prod could be used instead of PPoint
def iso_Prod_PPoint {α : Type} : Iso (Prod α α) (PPoint α) := by
constructor
case into => apply (fun prod => PPoint.mk prod.fst prod.snd)
case outOf => apply (fun point => Prod.mk point.x point.y)
case comp1 => funext _ <;> simp
case comp2 => funext _ <;> simp
-- ANCHOR: Sum
inductive Sum (α : Type) (β : Type) : Type where
| inl : α → Sum α β
| inr : β → Sum α β
-- ANCHOR_END: Sum
-- ANCHOR: Sumαβ
%show_term Sumαβ := {α β : Type} → Sum α β → α ⊕ β
-- ANCHOR_END: Sumαβ
-- ANCHOR: FakeSum
%show_name Sum as fakeSum
%show_name Sum.inl as fakeSum.inl
%show_name Sum.inr as fakeSum.inr
namespace Sum
%show_name inl as fakeInl
%show_name inr as fakeInr
end Sum
-- ANCHOR_END: FakeSum
-- ANCHOR: Unit
inductive Unit : Type where
| unit : Unit
-- ANCHOR_END: Unit
%show_name Unit as fakeUnit
section
open Unit
%show_name unit as fakeunit
end
inductive Empty : Type where
end StdLibNoUni
similar datatypes Option StdLibNoUni.Option
similar datatypes Prod StdLibNoUni.Prod
similar datatypes Sum StdLibNoUni.Sum
similar datatypes PUnit StdLibNoUni.Unit
similar datatypes Empty StdLibNoUni.Empty
-- ANCHOR: PetName
def PetName : Type := String ⊕ String
-- ANCHOR_END: PetName
open SubVerso.Examples in
%show_name PetName as PetName.name
-- ANCHOR: animals
def animals : List PetName :=
[Sum.inl "Spot", Sum.inr "Tiger", Sum.inl "Fifi",
Sum.inl "Rex", Sum.inr "Floof"]
-- ANCHOR_END: animals
-- ANCHOR: howManyDogs
def howManyDogs (pets : List PetName) : Nat :=
match pets with
| [] => 0
| Sum.inl _ :: morePets => howManyDogs morePets + 1
| Sum.inr _ :: morePets => howManyDogs morePets
-- ANCHOR_END: howManyDogs
section
variable (morePets : List PetName)
-- ANCHOR: howManyDogsAdd
example : (
howManyDogs morePets + 1
) = (
(howManyDogs morePets) + 1
) := rfl
-- ANCHOR_END: howManyDogsAdd
end
/-- info:
3
-/
#check_msgs in
-- ANCHOR: dogCount
#eval howManyDogs animals
-- ANCHOR_END: dogCount
-- ANCHOR: unitParens
example : Unit := (() : Unit)
-- ANCHOR_END: unitParens
open SubVerso.Examples in
-- ANCHOR: ArithExpr
inductive ArithExpr (ann : Type) : Type where
| int : ann → Int → ArithExpr ann
| plus : ann → ArithExpr ann → ArithExpr ann → ArithExpr ann
| minus : ann → ArithExpr ann → ArithExpr ann → ArithExpr ann
| times : ann → ArithExpr ann → ArithExpr ann → ArithExpr ann
-- ANCHOR_END: ArithExpr
-- ANCHOR: ArithExprEx
section
open SubVerso.Examples
structure SourcePos where
line : Nat
column : Nat
%show_term «ArithExpr SourcePos» := ArithExpr SourcePos
%show_term «ArithExpr Unit» := ArithExpr Unit
%show_name SourcePos as SourcePos.name
end
-- ANCHOR_END: ArithExprEx
-- ANCHOR: nullOne
example : Option (Option Int) := none
-- ANCHOR_END: nullOne
-- ANCHOR: nullTwo
example : Option (Option Int) := some none
-- ANCHOR_END: nullTwo
-- ANCHOR: nullThree
example : Option (Option Int) := some (some 360)
-- ANCHOR_END: nullThree
namespace Floop
open SubVerso.Examples
-- ANCHOR: headHuh
def List.head? {α : Type} (xs : List α) : Option α :=
match xs with
| [] => none
| y :: _ => some y
-- ANCHOR_END: headHuh
%show_name List.head? as fakeHead?
/-- info:
some 2
-/
#check_msgs in
-- ANCHOR: headSome
#eval primesUnder10.head?
-- ANCHOR_END: headSome
/--
error: don't know how to synthesize implicit argument `α`
@_root_.List.head? ?m.3 []
context:
⊢ Type ?u.70597
---
error: don't know how to synthesize implicit argument `α`
@List.nil ?m.3
context:
⊢ Type ?u.70597
-/
#check_msgs in
-- ANCHOR: headNoneBad
#eval [].head?
-- ANCHOR_END: headNoneBad
/--
error: don't know how to synthesize implicit argument `α`
@_root_.List.head? ?m.3 []
context:
⊢ Type ?u.70606
---
error: don't know how to synthesize implicit argument `α`
@List.nil ?m.3
context:
⊢ Type ?u.70606
-/
#check_msgs in
-- ANCHOR: headNoneBad2
#eval [].head?
-- ANCHOR_END: headNoneBad2
/-- info:
none
-/
#check_msgs in
-- ANCHOR: headNone
#eval [].head? (α := Int)
-- ANCHOR_END: headNone
/-- info:
none
-/
#check_msgs in
-- ANCHOR: headNoneTwo
#eval ([] : List Int).head?
-- ANCHOR_END: headNoneTwo
def List.final? {α : Type} (xs : List α) : Option α :=
match xs with
| [] => none
| [y] => some y
| y1 :: y2 :: ys => final? (y2::ys)
end Floop
open SubVerso.Examples in
%show_term αxβ := (α β : Type) → Prod α β → α × β
namespace StructNotation
-- ANCHOR: fivesStruct
def fives : String × Int := { fst := "five", snd := 5 }
-- ANCHOR_END: fivesStruct
end StructNotation
-- ANCHOR: fives
def fives : String × Int := ("five", 5)
-- ANCHOR_END: fives
example : StructNotation.fives = fives := by rfl
namespace Nested
-- ANCHOR: sevensNested
def sevens : String × (Int × Nat) := ("VII", (7, 4 + 3))
-- ANCHOR_END: sevensNested
end Nested
-- ANCHOR: sevens
def sevens : String × Int × Nat := ("VII", 7, 4 + 3)
-- ANCHOR_END: sevens
-- Backing up that they are equivalent
example : Nested.sevens = sevens := by rfl
example : sevens.swap = ((7, 7), "VII") := by rfl
def findString (haystack : List String) (needle : String) : Option Int :=
match haystack with
| [] => none
| x :: xs =>
if needle == x then
some 0
else match findString xs needle with
| none => none
| some i => some (i + 1)
inductive LinkedList : Type -> Type where
| nil : LinkedList α
| cons : α → LinkedList α → LinkedList α
def List.findFirst? {α : Type} (xs : List α) (predicate : α → Bool) : Option α :=
match xs with
| [] => none
| y :: ys => if predicate y then some y else ys.findFirst? predicate
-- ANCHOR: Sign
inductive Sign where
| pos
| neg
-- ANCHOR_END: Sign
open SubVerso.Examples in
-- ANCHOR: posOrNegThree
def posOrNegThree (s : Sign) :
match s with | Sign.pos => Nat | Sign.neg => Int :=
match s with
| Sign.pos => (3 : Nat)
| Sign.neg => (-3 : Int)
-- ANCHOR_END: posOrNegThree
section
open SubVerso.Examples
%show_name posOrNegThree as posOrNegThree.name
%show_name Sign.pos as Sign.pos.name
%show_name Sign.neg as Sign.neg.name
open Sign
%show_name pos as pos.name
%show_name neg as neg.name
end
evaluation steps {{{ posOrNegThreePos }}}
-- ANCHOR: posOrNegThreePos
(posOrNegThree Sign.pos :
match Sign.pos with | Sign.pos => Nat | Sign.neg => Int)
===>
((match Sign.pos with
| Sign.pos => (3 : Nat)
| Sign.neg => (-3 : Int)) :
match Sign.pos with | Sign.pos => Nat | Sign.neg => Int)
===>
((3 : Nat) : Nat)
===>
3
-- ANCHOR_END: posOrNegThreePos
end evaluation steps
def take (n : Nat) (xs : List α) : List α :=
match n, xs with
| _, [] => []
| Nat.zero, _ => []
| Nat.succ n', x :: xs => x :: take n' xs
/-- info:
["bolete", "oyster"]
-/
#check_msgs in
-- ANCHOR: takeThree
#eval take 3 ["bolete", "oyster"]
-- ANCHOR_END: takeThree
/-- info:
["bolete"]
-/
#check_msgs in
-- ANCHOR: takeOne
#eval take 1 ["bolete", "oyster"]
-- ANCHOR_END: takeOne
-- sum notation
example : (Sum α β) = (α ⊕ β) := by rfl
def Exhausts (α : Type) (xs : List α) := (x : α) → x ∈ xs
example : Exhausts (Bool × Unit) [(true, Unit.unit), (false, Unit.unit)] := by
intro ⟨ fst, snd ⟩
cases fst <;> cases snd <;> simp
example : Exhausts (Bool ⊕ Unit) [Sum.inl true, Sum.inl false, Sum.inr Unit.unit] := by
intro x
cases x with
| inl y => cases y <;> simp
| inr y => cases y <;> simp
example : Exhausts (Bool ⊕ Empty) [Sum.inl true, Sum.inl false] := by
intro x
cases x with
| inl y => cases y <;> repeat constructor
| inr y => cases y
discarding
/--
error: Invalid universe level in constructor `MyType.ctor`: Parameter `α` has type
Type
at universe level
2
which is not less than or equal to the inductive type's resulting universe level
1
-/
#check_msgs in
-- ANCHOR: TypeInType
inductive MyType : Type where
| ctor : (α : Type) → α → MyType
-- ANCHOR_END: TypeInType
stop discarding
discarding
/-- error:
(kernel) arg #1 of 'MyType.ctor' has a non positive occurrence of the datatypes being declared
-/
#check_msgs in
-- ANCHOR: Positivity
inductive MyType : Type where
| ctor : (MyType → Int) → MyType
-- ANCHOR_END: Positivity
stop discarding
#eval if let Option.some x := Option.some 5 then x else 55
section
open SubVerso.Examples
discarding
/-- error:
type expected, got
(MyType : Type → Type)
-/
#check_msgs in
-- ANCHOR: MissingTypeArg
inductive MyType (α : Type) : Type where
| ctor : α → MyType
-- ANCHOR_END: MissingTypeArg
stop discarding
-- ANCHOR: MyTypeDef
inductive MyType (α : Type) : Type where
| ctor : α → MyType α
-- ANCHOR_END: MyTypeDef
-- ANCHOR: MissingTypeArgT
example : Type → Type := MyType
-- ANCHOR_END: MissingTypeArgT
%show_name MyType as MyType.name
section
open MyType
%show_name ctor as MyType.ctor.name
end
/-- error:
type expected, got
(MyType : Type → Type)
-/
#check_msgs in
-- ANCHOR: MissingTypeArg2
def ofFive : MyType := ctor 5
-- ANCHOR_END: MissingTypeArg2
-- ANCHOR: WoodSplittingTool
inductive WoodSplittingTool where
| axe
| maul
| froe
-- ANCHOR_END: WoodSplittingTool
/-- info: WoodSplittingTool.axe -/
#check_msgs in
-- ANCHOR: evalAxe
#eval WoodSplittingTool.axe
-- ANCHOR_END: evalAxe
-- ANCHOR: allTools
def allTools : List WoodSplittingTool := [
WoodSplittingTool.axe,
WoodSplittingTool.maul,
WoodSplittingTool.froe
]
-- ANCHOR_END: allTools
/--
error: could not synthesize a `ToExpr`, `Repr`, or `ToString` instance for type
List WoodSplittingTool
-/
#check_msgs in
-- ANCHOR: evalAllTools
#eval allTools
-- ANCHOR_END: evalAllTools
-- ANCHOR: Firewood
inductive Firewood where
| birch
| pine
| beech
deriving Repr
-- ANCHOR_END: Firewood
-- ANCHOR: allFirewood
def allFirewood : List Firewood := [
Firewood.birch,
Firewood.pine,
Firewood.beech
]
-- ANCHOR_END: allFirewood
/-- info: [Firewood.birch, Firewood.pine, Firewood.beech] -/
#check_msgs in
-- ANCHOR: evalAllFirewood
#eval allFirewood
-- ANCHOR_END: evalAllFirewood
end
-- Example solution
def zip {α β : Type} (xs : List α) (ys : List β) : List (α × β) :=
match xs with
| [] => []
| x :: xs' =>
match ys with
| [] => []
| y :: ys' => (x, y) :: zip xs' ys'
variable {α β : Type}
open SubVerso.Examples in
/--
error: fail to show termination for
sameLength
with errors
failed to infer structural recursion:
Not considering parameter α of sameLength:
it is unchanged in the recursive calls
Not considering parameter β of sameLength:
it is unchanged in the recursive calls
Cannot use parameter xs:
failed to eliminate recursive application
sameLength xs' ys'
Cannot use parameter ys:
failed to eliminate recursive application
sameLength xs' ys'
Could not find a decreasing measure.
The basic measures relate at each recursive call as follows:
(<, ≤, =: relation proved, ? all proofs failed, _: no proof attempted)
xs ys
1) 1816:28-46 ? ?
Please use `termination_by` to specify a decreasing measure.
-/
#check_msgs in
-- ANCHOR: sameLengthPair
def sameLength (xs : List α) (ys : List β) : Bool :=
match (xs, ys) with
| ([], []) => true
| (x :: xs', y :: ys') => sameLength xs' ys'
| _ => false
-- ANCHOR_END: sameLengthPair
namespace Nested
-- ANCHOR: sameLengthOk1
def sameLength (xs : List α) (ys : List β) : Bool :=
match xs with
| [] =>
match ys with
| [] => true
| _ => false
| x :: xs' =>
match ys with
| y :: ys' => sameLength xs' ys'
| _ => false
-- ANCHOR_END: sameLengthOk1
end Nested
namespace Both
-- ANCHOR: sameLengthOk2
def sameLength (xs : List α) (ys : List β) : Bool :=
match xs, ys with
| [], [] => true
| x :: xs', y :: ys' => sameLength xs' ys'
| _, _ => false
-- ANCHOR_END: sameLengthOk2
end Both
namespace AutoImpl
-- ANCHOR: lengthImpAuto
def length (xs : List α) : Nat :=
match xs with
| [] => 0
| y :: ys => Nat.succ (length ys)
-- ANCHOR_END: lengthImpAuto
end AutoImpl
namespace MatchDef
variable {α : Type}
open SubVerso.Examples
-- ANCHOR: lengthMatchDef
def length : List α → Nat
| [] => 0
| y :: ys => Nat.succ (length ys)
-- ANCHOR_END: lengthMatchDef
end MatchDef
section
variable {α : Type}
open SubVerso.Examples in
-- ANCHOR: drop
def drop : Nat → List α → List α
| Nat.zero, xs => xs
| _, [] => []
| Nat.succ n, x :: xs => drop n xs
-- ANCHOR_END: drop
-- ANCHOR: fromOption
def fromOption (default : α) : Option α → α
| none => default
| some x => x
-- ANCHOR_END: fromOption
end
/-- info:
"salmonberry"
-/
#check_msgs in
-- ANCHOR: getD
#eval (some "salmonberry").getD ""
-- ANCHOR_END: getD
/-- info:
""
-/
#check_msgs in
-- ANCHOR: getDNone
#eval none.getD ""
-- ANCHOR_END: getDNone
section
variable {α β : Type}
namespace BadUnzip
open SubVerso.Examples
-- ANCHOR: unzipBad
def unzip : List (α × β) → List α × List β
| [] => ([], [])
| (x, y) :: xys =>
(x :: (unzip xys).fst, y :: (unzip xys).snd)
-- ANCHOR_END: unzipBad
%show_name unzip as unzipBad.name
end BadUnzip
-- ANCHOR: unzip
def unzip : List (α × β) → List α × List β
| [] => ([], [])
| (x, y) :: xys =>
let unzipped : List α × List β := unzip xys
(x :: unzipped.fst, y :: unzipped.snd)
-- ANCHOR_END: unzip
open SubVerso.Examples in
%show_name unzip as unzip.name
open SubVerso.Examples in
-- ANCHOR: reverse
def reverse (xs : List α) : List α :=
let rec helper : List α → List α → List α
| [], soFar => soFar
| y :: ys, soFar => helper ys (y :: soFar)
helper xs []
-- ANCHOR_END: reverse
end
namespace WithPattern
variable {α β : Type}
-- ANCHOR: unzipPat
def unzip : List (α × β) → List α × List β
| [] => ([], [])
| (x, y) :: xys =>
let (xs, ys) : List α × List β := unzip xys
(x :: xs, y :: ys)
-- ANCHOR_END: unzipPat
end WithPattern
namespace NT
variable {α β : Type}
open SubVerso.Examples
-- ANCHOR: unzipNT
def unzip : List (α × β) → List α × List β
| [] => ([], [])
| (x, y) :: xys =>
let unzipped := unzip xys
(x :: unzipped.fst, y :: unzipped.snd)
-- ANCHOR_END: unzipNT
-- ANCHOR: idA
def id (x : α) : α := x
-- ANCHOR_END: idA
end NT
namespace NRT
variable {α β : Type}
open SubVerso.Examples
-- ANCHOR: unzipNRT
def unzip (pairs : List (α × β)) :=
match pairs with
| [] => ([], [])
| (x, y) :: xys =>
let unzipped := unzip xys
(x :: unzipped.fst, y :: unzipped.snd)
-- ANCHOR_END: unzipNRT
-- ANCHOR: idB
def id (x : α) := x
-- ANCHOR_END: idB
end NRT
namespace ReallyNoTypes
open SubVerso.Examples
/--
error: Failed to infer type of definition `id`
---
error: Failed to infer type of binder `x`
-/
#check_msgs in
-- ANCHOR: identNoTypes
def id x := x
-- ANCHOR_END: identNoTypes
/--
error: Invalid match expression: This pattern contains metavariables:
[]
-/
#check_msgs in
-- ANCHOR: unzipNoTypesAtAll
def unzip pairs :=
match pairs with
| [] => ([], [])
| (x, y) :: xys =>
let unzipped := unzip xys
(x :: unzipped.fst, y :: unzipped.snd)
-- ANCHOR_END: unzipNoTypesAtAll
end ReallyNoTypes
/-- info:
14 : Nat
-/
#check_msgs in
-- ANCHOR: fourteenNat
#check 14
-- ANCHOR_END: fourteenNat
/-- info:
14 : Int
-/
#check_msgs in
-- ANCHOR: fourteenInt
#check (14 : Int)
-- ANCHOR_END: fourteenInt
namespace Match
variable {α β : Type}
open SubVerso.Examples
-- ANCHOR: dropMatch
def drop (n : Nat) (xs : List α) : List α :=
match n, xs with
| Nat.zero, ys => ys
| _, [] => []
| Nat.succ n , y :: ys => drop n ys
-- ANCHOR_END: dropMatch
-- ANCHOR: evenFancy
def even : Nat → Bool
| 0 => true
| n + 1 => not (even n)
-- ANCHOR_END: evenFancy
namespace Explicit
-- ANCHOR: explicitHalve
def halve : Nat → Nat
| Nat.zero => 0
| Nat.succ Nat.zero => 0
| Nat.succ (Nat.succ n) => halve n + 1
-- ANCHOR_END: explicitHalve
end Explicit
-- ANCHOR: halve
def halve : Nat → Nat
| 0 => 0
| 1 => 0
| n + 2 => halve n + 1
-- ANCHOR_END: halve
-- ANCHOR: halveParens
%show_term halveParens := fun n => [(halve n) + 1, halve (n + 1)]
-- ANCHOR_END: halveParens
example : Explicit.halve = halve := by
funext x
fun_induction halve x <;> simp [Explicit.halve, *]
namespace Oops
/--
error: Invalid pattern(s): `n` is an explicit pattern variable, but it only occurs in positions that are inaccessible to pattern matching:
.(Nat.add 2 n)
-/
#check_msgs in
-- ANCHOR: halveFlippedPat
def halve : Nat → Nat
| 0 => 0
| 1 => 0
| 2 + n => halve n + 1
-- ANCHOR_END: halveFlippedPat
end Oops
end Match
evaluation steps {{{ incrSteps }}}
-- ANCHOR: incrSteps
fun x => x + 1
===>
(· + 1)
===>
Nat.succ
-- ANCHOR_END: incrSteps
end evaluation steps
/-- info:
fun x => x + 1 : Nat → Nat
-/
#check_msgs in
-- ANCHOR: incr
#check fun x => x + 1
-- ANCHOR_END: incr
/-- info:
fun x => x + 1 : Int → Int
-/
#check_msgs in
-- ANCHOR: incrInt
#check fun (x : Int) => x + 1
-- ANCHOR_END: incrInt
/-- info:
fun {α} x => x : {α : Type} → α → α
-/
#check_msgs in
-- ANCHOR: identLambda
#check fun {α : Type} (x : α) => x
-- ANCHOR_END: identLambda
/-- info:
fun x =>
match x with
| 0 => none
| n.succ => some n : Nat → Option Nat
-/
#check_msgs in
-- ANCHOR: predHuh
#check fun
| 0 => none
| n + 1 => some n
-- ANCHOR_END: predHuh
namespace Double
-- ANCHOR: doubleLambda
def double : Nat → Nat := fun
| 0 => 0
| k + 1 => double k + 2
-- ANCHOR_END: doubleLambda
end Double
evaluation steps {{{ funPair }}}
-- ANCHOR: funPair
(· + 5, 3)
-- ANCHOR_END: funPair
end evaluation steps
evaluation steps {{{ pairFun }}}
-- ANCHOR: pairFun
((· + 5), 3)
-- ANCHOR_END: pairFun
end evaluation steps
evaluation steps {{{ twoDots }}}
-- ANCHOR: twoDots
(· , ·) 1 2
===>
(1, ·) 2
===>
(1, 2)
-- ANCHOR_END: twoDots
end evaluation steps
/-- info:
10
-/
#check_msgs in
-- ANCHOR: applyLambda
#eval (fun x => x + x) 5
-- ANCHOR_END: applyLambda
/-- info:
10
-/
#check_msgs in
-- ANCHOR: applyCdot
#eval (· * 2) 5
-- ANCHOR_END: applyCdot
-- ANCHOR: NatDouble
def Nat.double (x : Nat) : Nat := x + x
-- ANCHOR_END: NatDouble
open SubVerso.Examples in
%show_name Nat.double as Nat.double.name
section
open SubVerso.Examples
open Nat
%show_name double as double.name
end
/-- info:
8
-/
#check_msgs in
-- ANCHOR: NatDoubleFour
#eval (4 : Nat).double
-- ANCHOR_END: NatDoubleFour
-- ANCHOR: NewNamespace
namespace NewNamespace
def triple (x : Nat) : Nat := 3 * x
def quadruple (x : Nat) : Nat := 2 * x + 2 * x
end NewNamespace
-- ANCHOR_END: NewNamespace
section
open SubVerso.Examples
open NewNamespace
%show_name triple
%show_name quadruple
end
/-- info:
NewNamespace.triple (x : Nat) : Nat
-/
#check_msgs in
-- ANCHOR: tripleNamespace
#check NewNamespace.triple
-- ANCHOR_END: tripleNamespace
/-- info:
NewNamespace.quadruple (x : Nat) : Nat
-/
#check_msgs in
-- ANCHOR: quadrupleNamespace
#check NewNamespace.quadruple
-- ANCHOR_END: quadrupleNamespace
-- ANCHOR: quadrupleOpenDef
def timesTwelve (x : Nat) :=
open NewNamespace in
quadruple (triple x)
-- ANCHOR_END: quadrupleOpenDef
open SubVerso.Examples in
%show_name timesTwelve
example : timesTwelve 2 = 24 := by rfl
/-- info:
NewNamespace.quadruple (x : Nat) : Nat
-/
#check_msgs in
-- ANCHOR: quadrupleNamespaceOpen
open NewNamespace in
#check quadruple
-- ANCHOR_END: quadrupleNamespaceOpen
/-- info:
"three fives is 15"
-/
#check_msgs in
-- ANCHOR: interpolation
#eval s!"three fives is {NewNamespace.triple 5}"
-- ANCHOR_END: interpolation
/--
error: failed to synthesize
ToString (Nat → Nat)
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
---
info: toString "three fives is " ++ sorry : String
-/
#check_msgs in
-- ANCHOR: interpolationOops
#check s!"three fives is {NewNamespace.triple}"
-- ANCHOR_END: interpolationOops
-- ANCHOR: Inline
inductive Inline : Type where
| lineBreak
| string : String → Inline
| emph : Inline → Inline
| strong : Inline → Inline
-- ANCHOR_END: Inline
namespace WithMatch
-- ANCHOR: inlineStringHuhMatch
def Inline.string? (inline : Inline) : Option String :=
match inline with
| Inline.string s => some s
| _ => none
-- ANCHOR_END: inlineStringHuhMatch
end WithMatch
-- ANCHOR: inlineStringHuh
def Inline.string? (inline : Inline) : Option String :=
if let Inline.string s := inline then
some s
else none
-- ANCHOR_END: inlineStringHuh
example : WithMatch.Inline.string? = Inline.string? := by rfl
-- ANCHOR: pointCtor
example : (Point.mk 1 2 : (Point)) = ({ x := 1, y := 2 } : (Point)) := rfl
-- ANCHOR_END: pointCtor
-- ANCHOR: pointBraces
example : ({ x := 1, y := 2 } : (Point)) = (Point.mk 1 2 : (Point)) := rfl
-- ANCHOR_END: pointBraces
-- ANCHOR: pointPos
example : (⟨1, 2⟩ : (Point)) = (Point.mk 1 2 : (Point)) := rfl
-- ANCHOR_END: pointPos
/-- error: Invalid `⟨...⟩` notation: The expected type of this term could not be determined -/
#check_msgs in
-- ANCHOR: pointPosEvalNoType
#eval ⟨1, 2⟩
-- ANCHOR_END: pointPosEvalNoType
/-- info:
{ x := 1.000000, y := 2.000000 }
-/
#check_msgs in
-- ANCHOR: pointPosWithType
#eval (⟨1, 2⟩ : Point)
-- ANCHOR_END: pointPosWithType
-- ANCHOR: swapLambda
example : (Point → Point) := fun (point : Point) => { x := point.y, y := point.x : Point }
-- ANCHOR_END: swapLambda
-- ANCHOR: subOneDots
example : ((· - 1) : (Int → Int)) = (fun x => x - 1 : (Int → Int)) := rfl
-- ANCHOR_END: subOneDots
open SubVerso.Examples
section
%show_term sizes := (α β : Type) → α → β → α ⊕ β → α × β
%show_term «Bool × Unit» := Bool × Unit
-- ANCHOR: BoolxUnit
%show_term BoolxUnit.vals : List (Bool × Unit) := [(true, Unit.unit), (false, Unit.unit)]
-- ANCHOR_END: BoolxUnit
%show_term «Bool ⊕ Unit» := Bool ⊕ Unit
-- ANCHOR: BooloUnit
%show_term BooloUnit.vals : List (Bool ⊕ Unit) := [Sum.inl true, Sum.inl false, Sum.inr Unit.unit]
-- ANCHOR_END: BooloUnit
end
section
open Point3D
%show_name z as Point3D.z.name
end
%show_name Point3D as Point3D.name
%show_term oak := "oak "
%show_term great := "great "
%show_term tree := "tree"
%show_name String.append
%show_name Nat as Nat.name
%show_name Nat.zero as Nat.zero.name
%show_name Nat.succ as Nat.succ.name
section
open Nat
%show_name succ as succ.name
%show_name zero as zero.name
end
section
open List
%show_name cons as cons.name
%show_name nil as nil.name
end
%show_name List.cons as List.cons.name
%show_name List.nil as List.nil.name
%show_name Prod as Prod.name
%show_name Prod.mk as Prod.mk.name
%show_name Prod.fst as Prod.fst.name
%show_name Prod.snd as Prod.snd.name
%show_name Sum as Sum.name
%show_name Sum.inl as Sum.inl.name
%show_name Sum.inr as Sum.inr.name
%show_name addPoints as addPoints.name
%show_name replaceX as replaceX.name
%show_name isZero as isZero.name
%show_name Float as Float.name
%show_name Int as Int.name
%show_name Bool as Bool.name
%show_name true
%show_name false
%show_name Bool.true
%show_name Bool.false
%show_name String as String.name
%show_name Hamster as Hamster.name
%show_name Book as Book.name
%show_name aStr as aStr.name
%show_name List as List.name
%show_name List.head as List.head.name
%show_name List.head? as List.head?.name
section
open List
%show_name head? as head?.name
end
%show_name List.head! as List.head!.name
%show_name List.headD as List.headD.name
%show_name Option.getD as Option.getD.name
%show_name Empty as Empty.name
%show_name Unit as Unit.name
%show_name Unit.unit as Unit.unit.name
%show_name Option as Option.name
%show_name some as some.name
%show_name none as none.name
%show_name Option.some as Option.some.name
%show_name Option.none as Option.none.name
%show_name Point.mk as Point.mk
%show_name Point.x as Point.x.name
%show_name Point.y as Point.y.name
%show_name fourAndThree as fourAndThree.name
%show_term «Option Int» := Option Int
%show_term «Option (List String)» := Option (List String)
%show_term «Nat→Bool» := Nat → Bool
%show_term «Nat→Nat→Nat» := Nat → Nat → Nat
%show_term «Nat→(Nat→Nat)» := Nat → (Nat → Nat)
%show_name maximum as maximum.name
%show_name spaceBetween as spaceBetween.name
-- ANCHOR: evalEx
%show_term ex1 := 42 + 19
%show_term ex2 := String.append "A" (String.append "B" "C")
%show_term ex3 := String.append (String.append "A" "B") "C"
%show_term ex4 := if 3 == 3 then 5 else 7
%show_term ex5 := if 3 == 4 then "equal" else "not equal"
-- ANCHOR_END: evalEx
%show_term zero := 0
%show_term «0» := 0
%show_term «5» := 5
%show_term «Type» := Type
%show_term «Type→Type» := Type → Type
%show_term «List Nat» := List Nat
%show_term «List String» := List String
%show_term «List (List Point)» := List (List Point)
%show_term «Prod Nat String» := Prod Nat String
%show_term «Prod Nat Nat» := Prod Nat Nat
%show_term «PPoint Nat» := PPoint Nat
%show_term «Sum String Int» := Sum String Int
%show_name List.length as List.length.name
%show_name List.map as List.map.name
%show_name Array.map as Array.map.name
section
-- ANCHOR: distr
%show_term distr := (α β γ : Type) → α × (β ⊕ γ) → (α × β) ⊕ (α × γ) → Bool × α → α ⊕ α
-- ANCHOR_END: distr
end
-- ANCHOR: α
example : Type 1 := ({α : Type} → α → Nat : Type 1)
-- ANCHOR_END: α
namespace Oops
axiom mySorry : α
scoped macro "…" : term => `(mySorry)
noncomputable section
-- ANCHOR: List.findFirst?Ex
def List.findFirst? {α : Type} (xs : List α) (predicate : α → Bool) : Option α := …
-- ANCHOR_END: List.findFirst?Ex
%show_name List.findFirst?
-- ANCHOR: Prod.switchEx
def Prod.switch {α β : Type} (pair : α × β) : β × α := …
-- ANCHOR_END: Prod.switchEx
%show_name Prod.switch
-- ANCHOR: zipEx
def zip {α β : Type} (xs : List α) (ys : List β) : List (α × β) := …
-- ANCHOR_END: zipEx
%show_name zip
end
end Oops
-- ANCHOR: fragments
example := [List Nat, List String, List (List Point), PPoint Int, Nat, Bool × Unit, Bool ⊕ Unit, Empty, Option (List String)]
example := [Prod Nat String, Prod Nat Nat, Sum String Int]
example := Point3D.z
example := {α : Type} → Nat → α → List α
example := Option (String ⊕ (Nat × String))
example := @Option.getD
example := Nat.double
section
open Nat
example := double
end
example := @List.nil
example := @List.cons
example := @List.head!
example := @List.head?
example := @List.headD
example := @List.head
example := @List.map
example := @Array.map
section
open List
example := @map
example := @head?
end
-- ANCHOR_END: fragments
-- ANCHOR: ProdSugar
example {α β : Type} : (
Prod α β
) = (
α × β
) := rfl
-- ANCHOR_END: ProdSugar
-- ANCHOR: SumSugar
example {α β : Type} : (
Sum α β
) = (
α ⊕ β
) := rfl
-- ANCHOR_END: SumSugar
-- ANCHOR: SumProd
section
variable (α β : Type)
example := α ⊕ β
example := α × β
end
-- ANCHOR_END: SumProd
namespace Ex
-- ANCHOR: RectangularPrism
structure RectangularPrism where
-- Exercise
def volume : RectangularPrism → Float := fun _ => 0.0 -- Exercise
structure Segment where
-- Exercise
def length : Segment → Float := fun _ => 0.0 -- Exercise
-- ANCHOR_END: RectangularPrism |
fp-lean/examples/Examples/SpecialTypes.lean | -- ANCHOR: all
example := List
example := [UInt8, UInt16, UInt32, UInt64, USize, Int8, Int16, Int32, Int64, ISize]
example := Fin (2 ^ 32)
example := [Nat, List Unit, String, Int, Char, List Char]
example {w} := BitVec w
example := [true, false]
example {x : α} := [some x, none]
example := ∀ {n k : Nat}, n ≠ 0 → k ≠ 0 → n + k ≠ 0
example := [Add, Mul, ToString]
example := Nat.succ
section
universe u
example := Sort u
end
-- ANCHOR_END: all
-- ANCHOR: sequences
section
example {α} := [List α, Array α]
open Array
example : Array α → List α := toList
end
-- ANCHOR_END: sequences
-- ANCHOR: StringDetail
section
open String
example : String → List Char := data
end
-- ANCHOR_END: StringDetail |
fp-lean/examples/Examples/Props.lean | import ExampleSupport
import Examples.Intro
-- ANCHOR: woodlandCritters
def woodlandCritters : List String :=
["hedgehog", "deer", "snail"]
-- ANCHOR_END: woodlandCritters
-- ANCHOR: animals
def hedgehog := woodlandCritters[0]
def deer := woodlandCritters[1]
def snail := woodlandCritters[2]
-- ANCHOR_END: animals
/--
error: failed to prove index is valid, possible solutions:
- Use `have`-expressions to prove the index is valid
- Use `a[i]!` notation instead, runtime check is performed, and 'Panic' error message is produced if index is not valid
- Use `a[i]?` notation instead, result is an `Option` type
- Use `a[i]'h` notation instead, where `h` is a proof that index is valid
⊢ 3 < woodlandCritters.length
-/
#check_msgs in
--- ANCHOR: outOfBounds
def oops := woodlandCritters[3]
--- ANCHOR_END: outOfBounds
-- ANCHOR: onePlusOneIsTwo
def onePlusOneIsTwo : 1 + 1 = 2 := rfl
-- ANCHOR_END: onePlusOneIsTwo
/--
error: Type mismatch
rfl
has type
?m.16 = ?m.16
but is expected to have type
1 + 1 = 15
---
error: Not a definitional equality: the left-hand side
1 + 1
is not definitionally equal to the right-hand side
15
-/
#check_msgs in
-- ANCHOR: onePlusOneIsFifteen
def onePlusOneIsFifteen : 1 + 1 = 15 := rfl
-- ANCHOR_END: onePlusOneIsFifteen
namespace Foo
-- ANCHOR: onePlusOneIsTwoProp
def OnePlusOneIsTwo : Prop := 1 + 1 = 2
theorem onePlusOneIsTwo : OnePlusOneIsTwo := rfl
-- ANCHOR_END: onePlusOneIsTwoProp
discarding
/-- error: `simp` made no progress -/
#check_msgs in
-- ANCHOR: onePlusOneIsStillTwo
theorem onePlusOneIsStillTwo : OnePlusOneIsTwo := by simp
-- ANCHOR_END: onePlusOneIsStillTwo
stop discarding
/--
error: failed to synthesize
Decidable OnePlusOneIsTwo
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: onePlusOneIsStillTwo2
theorem onePlusOneIsStillTwo : OnePlusOneIsTwo := by decide
-- ANCHOR_END: onePlusOneIsStillTwo2
end Foo
-- ANCHOR: implication
example {A B : Prop} := A → B
-- ANCHOR_END: implication
namespace Foo2
-- ANCHOR: onePlusOneIsTwoTactics
theorem onePlusOneIsTwo : 1 + 1 = 2 := by
decide
-- ANCHOR_END: onePlusOneIsTwoTactics
end Foo2
theorem oneLessThanFive : 1 < 5 := by simp
def second (xs : List α) (ok : xs.length ≥ 3) : α :=
xs[ 2 ]
example : String := second ["a", "b", "c", "d"] (by simp)
-- ANCHOR: connectiveTable
section
variable {A B : Prop}
example : True := (True.intro : True)
example : Prop := False
example := A ∧ B
example : A → B → A ∧ B := (And.intro : A → B → A ∧ B)
example := (Or.inl : A → A ∨ B)
example := (Or.inr : B → A ∨ B)
example := ¬A
end
-- ANCHOR_END: connectiveTable
-- ANCHOR: connectives
theorem onePlusOneOrLessThan : 1 + 1 = 2 ∨ 3 < 5 := by simp
theorem notTwoEqualFive : ¬(1 + 1 = 5) := by simp
theorem trueIsTrue : True := by simp
theorem trueOrFalse : True ∨ False := by simp
theorem falseImpliesTrue : False → True := by simp
-- ANCHOR_END: connectives
namespace Decide
-- ANCHOR: connectivesD
theorem onePlusOneOrLessThan : 1 + 1 = 2 ∨ 3 < 5 := by decide
theorem notTwoEqualFive : ¬(1 + 1 = 5) := by decide
theorem trueIsTrue : True := by decide
theorem trueOrFalse : True ∨ False := by decide
theorem falseImpliesTrue : False → True := by decide
-- ANCHOR_END: connectivesD
end Decide
def fooo : True ∧ True := And.intro True.intro True.intro
def bar : True ∨ False := Or.inl True.intro
namespace Connectives
variable {A B : Prop}
-- ANCHOR: SomeNats
example : List Nat := [0, 1, 2, 3, 4, 5]
-- ANCHOR_END: SomeNats
bookExample type {{{ TrueProp }}}
True
===>
Prop
end bookExample
bookExample type {{{ TrueIntro }}}
True.intro
===>
True
end bookExample
-- ANCHOR: AndProp
example : Prop := A ∧ B
-- ANCHOR_END: AndProp
-- ANCHOR: AndIntro
example : A → B → A ∧ B := And.intro
-- ANCHOR_END: AndIntro
-- ANCHOR: AndIntroEx
example : 1 + 1 = 2 ∧ "Str".append "ing" = "String" := And.intro rfl rfl
-- ANCHOR_END: AndIntroEx
-- ANCHOR: AndIntroExTac
theorem addAndAppend : 1 + 1 = 2 ∧ "Str".append "ing" = "String" := by
decide
-- ANCHOR_END: AndIntroExTac
-- ANCHOR: OrProp
example : Prop := A ∨ B
-- ANCHOR_END: OrProp
-- ANCHOR: OrIntro1
example : A → A ∨ B := Or.inl
-- ANCHOR_END: OrIntro1
-- ANCHOR: OrIntro2
example : B → A ∨ B := Or.inr
-- ANCHOR_END: OrIntro2
-- ANCHOR: impliesDef
example : (A → B) = (¬ A ∨ B) := by
simp only [eq_iff_iff]
constructor
. intro h
by_cases A
. apply Or.inr; simp_all
. apply Or.inl; simp_all
. intro h a
cases h <;> simp_all
-- ANCHOR_END: impliesDef
bookExample type {{{ OrIntroEx }}}
Or.inr rfl
===>
1 + 1 = 90 ∨ "Str".append "ing" = "String"
end bookExample
-- ANCHOR: OrIntroExTac
theorem addOrAppend : 1 + 1 = 90 ∨ "Str".append "ing" = "String" := by decide
-- ANCHOR_END: OrIntroExTac
set_option linter.unusedVariables false in
-- ANCHOR: andImpliesOr
theorem andImpliesOr : A ∧ B → A ∨ B :=
fun andEvidence =>
match andEvidence with
| And.intro a b => Or.inl a
-- ANCHOR_END: andImpliesOr
bookExample type {{{ FalseProp }}}
False
===>
Prop
end bookExample
end Connectives
discarding
/--
error: failed to prove index is valid, possible solutions:
- Use `have`-expressions to prove the index is valid
- Use `a[i]!` notation instead, runtime check is performed, and 'Panic' error message is produced if index is not valid
- Use `a[i]?` notation instead, result is an `Option` type
- Use `a[i]'h` notation instead, where `h` is a proof that index is valid
α : Type ?u.5228
xs : List α
⊢ 2 < xs.length
-/
#check_msgs in
-- ANCHOR: thirdErr
def third (xs : List α) : α := xs[2]
-- ANCHOR_END: thirdErr
stop discarding
-- ANCHOR: third
def third (xs : List α) (ok : xs.length > 2) : α := xs[2]
-- ANCHOR_END: third
example := 3 < woodlandCritters.length
example := 3 < List.length woodlandCritters
example := Nat → List String
example := Type
example := List (Nat × String × (Int → Float))
example := Prop
/-- info: "snail" -/
#check_msgs in
-- ANCHOR: thirdCritters
#eval third woodlandCritters (by decide)
-- ANCHOR_END: thirdCritters
/--
error: Tactic `decide` proved that the proposition
["rabbit"].length > 2
is false
-/
#check_msgs in
-- ANCHOR: thirdRabbitErr
#eval third ["rabbit"] (by decide)
-- ANCHOR_END: thirdRabbitErr
-- ANCHOR: thirdOption
def thirdOption (xs : List α) : Option α := xs[2]?
-- ANCHOR_END: thirdOption
---ANCHOR: OptionNames
section
variable (α : Type) (x : α)
example : Option α := none
example : Option α := some x
end
---ANCHOR_END: OptionNames
/-- info: some "snail" -/
#check_msgs in
-- ANCHOR: thirdOptionCritters
#eval thirdOption woodlandCritters
-- ANCHOR_END: thirdOptionCritters
/-- info: none -/
#check_msgs in
-- ANCHOR: thirdOptionTwo
#eval thirdOption ["only", "two"]
-- ANCHOR_END: thirdOptionTwo
/-- info: "deer" -/
#check_msgs in
-- ANCHOR: crittersBang
#eval woodlandCritters[1]!
-- ANCHOR_END: crittersBang
/--
error: failed to synthesize
Inhabited α
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: unsafeThird
def unsafeThird (xs : List α) : α := xs[2]!
-- ANCHOR_END: unsafeThird
/--
error: Function expected at
woodlandCritters
but this term has type
List String
Note: Expected a function because this term is being applied to the argument
[1]
-/
#check_msgs in
-- ANCHOR: extraSpace
#eval woodlandCritters [1]
-- ANCHOR_END: extraSpace
--ANCHOR: exercises
example : 2 + 3 = 5 := rfl
example : 15 - 8 = 7 := rfl
example : "Hello, ".append "world" = "Hello, world" := rfl
example : "Hello, ".append "world" = "Hello, world" := by decide
example : Prop := 5 < 18
--ANCHOR_END: exercises |
fp-lean/examples/Examples/Monads.lean | import ExampleSupport
import Examples.Classes
example := Monad
example := @HAdd.hAdd
example := @HMul.hMul
example := IO
-- ANCHOR: exceptNames
section
example := Except
example := @Except.ok
example := @Except.error
end
-- ANCHOR_END: exceptNames
namespace Monads.Option
variable {α : Type}
-- ANCHOR: first
def first (xs : List α) : Option α :=
xs[0]?
-- ANCHOR_END: first
-- ANCHOR: firstThird
def firstThird (xs : List α) : Option (α × α) :=
match xs[0]? with
| none => none
| some first =>
match xs[2]? with
| none => none
| some third =>
some (first, third)
-- ANCHOR_END: firstThird
-- ANCHOR: firstThirdFifth
def firstThirdFifth (xs : List α) : Option (α × α × α) :=
match xs[0]? with
| none => none
| some first =>
match xs[2]? with
| none => none
| some third =>
match xs[4]? with
| none => none
| some fifth =>
some (first, third, fifth)
-- ANCHOR_END: firstThirdFifth
-- ANCHOR: firstThirdFifthSeventh
def firstThirdFifthSeventh (xs : List α) : Option (α × α × α × α) :=
match xs[0]? with
| none => none
| some first =>
match xs[2]? with
| none => none
| some third =>
match xs[4]? with
| none => none
| some fifth =>
match xs[6]? with
| none => none
| some seventh =>
some (first, third, fifth, seventh)
-- ANCHOR_END: firstThirdFifthSeventh
namespace M
-- ANCHOR: andThenOption
def andThen (opt : Option α) (next : α → Option β) : Option β :=
match opt with
| none => none
| some x => next x
-- ANCHOR_END: andThenOption
-- ANCHOR: firstThirdandThen
def firstThird (xs : List α) : Option (α × α) :=
andThen xs[0]? fun first =>
andThen xs[2]? fun third =>
some (first, third)
-- ANCHOR_END: firstThirdandThen
namespace ExplicitParens
-- ANCHOR: firstThirdandThenExpl
def firstThird (xs : List α) : Option (α × α) :=
andThen xs[0]? (fun first =>
andThen xs[2]? (fun third =>
some (first, third)))
-- ANCHOR_END: firstThirdandThenExpl
end ExplicitParens
namespace Fixity
axiom w : Nat
axiom x : Nat
axiom y : Nat
axiom z : Nat
-- ANCHOR: plusFixity
example : w + x + y + z = (((w + x) + y) + z) := rfl
-- ANCHOR_END: plusFixity
-- ANCHOR: powFixity
example : w ^ x ^ y ^ z = (w ^ (x ^ (y ^ z))) := rfl
-- ANCHOR_END: powFixity
-- ANCHOR: plusTimesPrec
example : x + y * z = x + (y * z) := rfl
-- ANCHOR_END: plusTimesPrec
end Fixity
-- ANCHOR: andThenOptArr
infixl:55 " ~~> " => andThen
-- ANCHOR_END: andThenOptArr
-- ANCHOR: firstThirdInfix
def firstThirdInfix (xs : List α) : Option (α × α) :=
xs[0]? ~~> fun first =>
xs[2]? ~~> fun third =>
some (first, third)
-- ANCHOR_END: firstThirdInfix
-- ANCHOR: firstThirdFifthSeventInfix
def firstThirdFifthSeventh (xs : List α) : Option (α × α × α × α) :=
xs[0]? ~~> fun first =>
xs[2]? ~~> fun third =>
xs[4]? ~~> fun fifth =>
xs[6]? ~~> fun seventh =>
some (first, third, fifth, seventh)
-- ANCHOR_END: firstThirdFifthSeventInfix
end M
end Monads.Option
namespace FakeExcept
-- ANCHOR: Except
inductive Except (ε : Type) (α : Type) where
| error : ε → Except ε α
| ok : α → Except ε α
deriving BEq, Hashable, Repr
-- ANCHOR_END: Except
attribute [inherit_doc _root_.Except] Except
attribute [inherit_doc _root_.Except.ok] Except.ok
attribute [inherit_doc _root_.Except.error] Except.error
--ANCHOR: ExceptExtra
example := @Except.error
example := @Except.ok
--ANCHOR_END: ExceptExtra
end FakeExcept
similar datatypes FakeExcept.Except Except
namespace Monads.Err
-- ANCHOR: getExcept
def get (xs : List α) (i : Nat) : Except String α :=
match xs[i]? with
| none => Except.error s!"Index {i} not found (maximum is {xs.length - 1})"
| some x => Except.ok x
-- ANCHOR_END: getExcept
-- ANCHOR: ediblePlants
def ediblePlants : List String :=
["ramsons", "sea plantain", "sea buckthorn", "garden nasturtium"]
-- ANCHOR_END: ediblePlants
/-- info:
Except.ok "sea buckthorn"
-/
#check_msgs in
-- ANCHOR: success
#eval get ediblePlants 2
-- ANCHOR_END: success
/-- info:
Except.error "Index 4 not found (maximum is 3)"
-/
#check_msgs in
-- ANCHOR: failure
#eval get ediblePlants 4
-- ANCHOR_END: failure
-- ANCHOR: firstExcept
def first (xs : List α) : Except String α :=
get xs 0
-- ANCHOR_END: firstExcept
-- ANCHOR: firstThirdExcept
def firstThird (xs : List α) : Except String (α × α) :=
match get xs 0 with
| Except.error msg => Except.error msg
| Except.ok first =>
match get xs 2 with
| Except.error msg => Except.error msg
| Except.ok third =>
Except.ok (first, third)
-- ANCHOR_END: firstThirdExcept
-- ANCHOR: firstThirdFifthExcept
def firstThirdFifth (xs : List α) : Except String (α × α × α) :=
match get xs 0 with
| Except.error msg => Except.error msg
| Except.ok first =>
match get xs 2 with
| Except.error msg => Except.error msg
| Except.ok third =>
match get xs 4 with
| Except.error msg => Except.error msg
| Except.ok fifth =>
Except.ok (first, third, fifth)
-- ANCHOR_END: firstThirdFifthExcept
-- ANCHOR: firstThirdFifthSeventhExcept
def firstThirdFifthSeventh (xs : List α) : Except String (α × α × α × α) :=
match get xs 0 with
| Except.error msg => Except.error msg
| Except.ok first =>
match get xs 2 with
| Except.error msg => Except.error msg
| Except.ok third =>
match get xs 4 with
| Except.error msg => Except.error msg
| Except.ok fifth =>
match get xs 6 with
| Except.error msg => Except.error msg
| Except.ok seventh =>
Except.ok (first, third, fifth, seventh)
-- ANCHOR_END: firstThirdFifthSeventhExcept
-- ANCHOR: andThenExcept
def andThen (attempt : Except e α) (next : α → Except e β) : Except e β :=
match attempt with
| Except.error msg => Except.error msg
| Except.ok x => next x
-- ANCHOR_END: andThenExcept
namespace AndThen
-- ANCHOR: firstThirdAndThenExcept
def firstThird' (xs : List α) : Except String (α × α) :=
andThen (get xs 0) fun first =>
andThen (get xs 2) fun third =>
Except.ok (first, third)
-- ANCHOR_END: firstThirdAndThenExcept
end AndThen
-- ANCHOR: andThenExceptInfix
infixl:55 " ~~> " => andThen
-- ANCHOR_END: andThenExceptInfix
-- ANCHOR: okExcept
def ok (x : α) : Except ε α := Except.ok x
-- ANCHOR_END: okExcept
-- ANCHOR: failExcept
def fail (err : ε) : Except ε α := Except.error err
-- ANCHOR_END: failExcept
namespace Eff
-- ANCHOR: getExceptEffects
def get (xs : List α) (i : Nat) : Except String α :=
match xs[i]? with
| none => fail s!"Index {i} not found (maximum is {xs.length - 1})"
| some x => ok x
-- ANCHOR_END: getExceptEffects
end Eff
namespace WithInfix
-- ANCHOR: firstThirdInfixExcept
def firstThird (xs : List α) : Except String (α × α) :=
get xs 0 ~~> fun first =>
get xs 2 ~~> fun third =>
ok (first, third)
-- ANCHOR_END: firstThirdInfixExcept
-- ANCHOR: firstThirdFifthSeventInfixExcept
def firstThirdFifthSeventh (xs : List α) : Except String (α × α × α × α) :=
get xs 0 ~~> fun first =>
get xs 2 ~~> fun third =>
get xs 4 ~~> fun fifth =>
get xs 6 ~~> fun seventh =>
ok (first, third, fifth, seventh)
-- ANCHOR_END: firstThirdFifthSeventInfixExcept
end WithInfix
end Monads.Err
namespace Monads.Writer
-- ANCHOR: isEven
def isEven (i : Int) : Bool :=
i % 2 == 0
-- ANCHOR_END: isEven
example : isEven 34 := by decide
example : ¬isEven 39 := by decide
-- ANCHOR: sumAndFindEvensDirect
def sumAndFindEvens : List Int → List Int × Int
| [] => ([], 0)
| i :: is =>
let (moreEven, sum) := sumAndFindEvens is
(if isEven i then i :: moreEven else moreEven, sum + i)
-- ANCHOR_END: sumAndFindEvensDirect
namespace MoreMonadic
-- ANCHOR: sumAndFindEvensDirectish
def sumAndFindEvens : List Int → List Int × Int
| [] => ([], 0)
| i :: is =>
let (moreEven, sum) := sumAndFindEvens is
let (evenHere, ()) := (if isEven i then [i] else [], ())
(evenHere ++ moreEven, sum + i)
-- ANCHOR_END: sumAndFindEvensDirectish
end MoreMonadic
-- ANCHOR: inorderSum
def inorderSum : BinTree Int → List Int × Int
| BinTree.leaf => ([], 0)
| BinTree.branch l x r =>
let (leftVisited, leftSum) := inorderSum l
let (hereVisited, hereSum) := ([x], x)
let (rightVisited, rightSum) := inorderSum r
(leftVisited ++ hereVisited ++ rightVisited,
leftSum + hereSum + rightSum)
-- ANCHOR_END: inorderSum
-- ANCHOR: WithLog
structure WithLog (logged : Type) (α : Type) where
log : List logged
val : α
-- ANCHOR_END: WithLog
section
variable {logged : Type}
example := WithLog logged
end
deriving instance Repr for WithLog
-- ANCHOR: andThenWithLog
def andThen (result : WithLog α β) (next : β → WithLog α γ) : WithLog α γ :=
let {log := thisOut, val := thisRes} := result
let {log := nextOut, val := nextRes} := next thisRes
{log := thisOut ++ nextOut, val := nextRes}
-- ANCHOR_END: andThenWithLog
-- ANCHOR: okWithLog
def ok (x : β) : WithLog α β := {log := [], val := x}
-- ANCHOR_END: okWithLog
-- ANCHOR: save
def save (data : α) : WithLog α Unit :=
{log := [data], val := ()}
-- ANCHOR_END: save
namespace WithAndThen
-- ANCHOR: sumAndFindEvensAndThen
def sumAndFindEvens : List Int → WithLog Int Int
| [] => ok 0
| i :: is =>
andThen (if isEven i then save i else ok ()) fun () =>
andThen (sumAndFindEvens is) fun sum =>
ok (i + sum)
-- ANCHOR_END: sumAndFindEvensAndThen
-- ANCHOR: inorderSumAndThen
def inorderSum : BinTree Int → WithLog Int Int
| BinTree.leaf => ok 0
| BinTree.branch l x r =>
andThen (inorderSum l) fun leftSum =>
andThen (save x) fun () =>
andThen (inorderSum r) fun rightSum =>
ok (leftSum + x + rightSum)
-- ANCHOR_END: inorderSumAndThen
end WithAndThen
-- ANCHOR: infixAndThenLog
infixl:55 " ~~> " => andThen
-- ANCHOR_END: infixAndThenLog
namespace WithInfix
-- ANCHOR: withInfixLogging
def sumAndFindEvens : List Int → WithLog Int Int
| [] => ok 0
| i :: is =>
(if isEven i then save i else ok ()) ~~> fun () =>
sumAndFindEvens is ~~> fun sum =>
ok (i + sum)
def inorderSum : BinTree Int → WithLog Int Int
| BinTree.leaf => ok 0
| BinTree.branch l x r =>
inorderSum l ~~> fun leftSum =>
save x ~~> fun () =>
inorderSum r ~~> fun rightSum =>
ok (leftSum + x + rightSum)
-- ANCHOR_END: withInfixLogging
end WithInfix
end Monads.Writer
namespace Monads.State
-- ANCHOR: aTree
open BinTree in
def aTree :=
branch
(branch
(branch leaf "a" (branch leaf "b" leaf))
"c"
leaf)
"d"
(branch leaf "e" leaf)
-- ANCHOR_END: aTree
-- TODO include in text
deriving instance Repr for BinTree
-- ANCHOR: numberDirect
def number (t : BinTree α) : BinTree (Nat × α) :=
let rec helper (n : Nat) : BinTree α → (Nat × BinTree (Nat × α))
| BinTree.leaf => (n, BinTree.leaf)
| BinTree.branch left x right =>
let (k, numberedLeft) := helper n left
let (i, numberedRight) := helper (k + 1) right
(i, BinTree.branch numberedLeft (k, x) numberedRight)
(helper 0 t).snd
-- ANCHOR_END: numberDirect
/-- info:
BinTree.branch
(BinTree.branch
(BinTree.branch (BinTree.leaf) (0, "a") (BinTree.branch (BinTree.leaf) (1, "b") (BinTree.leaf)))
(2, "c")
(BinTree.leaf))
(3, "d")
(BinTree.branch (BinTree.leaf) (4, "e") (BinTree.leaf))
-/
#check_msgs in
-- ANCHOR: numberATree
#eval number aTree
-- ANCHOR_END: numberATree
-- ANCHOR: State
def State (σ : Type) (α : Type) : Type :=
σ → (σ × α)
-- ANCHOR_END: State
-- ANCHOR: get
def get : State σ σ :=
fun s => (s, s)
-- ANCHOR_END: get
-- ANCHOR: set
def set (s : σ) : State σ Unit :=
fun _ => (s, ())
-- ANCHOR_END: set
-- ANCHOR: andThenState
def andThen (first : State σ α) (next : α → State σ β) : State σ β :=
fun s =>
let (s', x) := first s
next x s'
infixl:55 " ~~> " => andThen
-- ANCHOR_END: andThenState
-- ANCHOR: okState
def ok (x : α) : State σ α :=
fun s => (s, x)
-- ANCHOR_END: okState
namespace Monadicish
-- ANCHOR: numberMonadicish
def number (t : BinTree α) : BinTree (Nat × α) :=
let rec helper : BinTree α → State Nat (BinTree (Nat × α))
| BinTree.leaf => ok BinTree.leaf
| BinTree.branch left x right =>
helper left ~~> fun numberedLeft =>
get ~~> fun n =>
set (n + 1) ~~> fun () =>
helper right ~~> fun numberedRight =>
ok (BinTree.branch numberedLeft (n, x) numberedRight)
(helper t 0).snd
-- ANCHOR_END: numberMonadicish
end Monadicish
example : number aTree = Monadicish.number aTree := by rfl
end Monads.State |
fp-lean/examples/Examples/MonadTransformers.lean | import ExampleSupport
import Examples.Monads
namespace Evaluator
inductive Prim where
| plus
| minus
| times
| div
def Var := String
deriving instance BEq, ToString for Var
inductive Expr where
| var : Var → Expr
| prim : Prim → Expr → Expr → Expr
| const : Int → Expr
| lett : Var → Expr → Expr → Expr
abbrev Env := List (Var × Int)
def Eval (α : Type) : Type :=
Env → Except String α
instance : Monad Eval where
pure x := fun _ => .ok x
bind m f := fun ρ =>
match m ρ with
| .error e => .error e
| .ok x => f x ρ
def currentEnv : Eval Env := fun ρ => .ok ρ
def bind (x : Var) (v : Int) (during : Eval α) : Eval α :=
fun ρ =>
during ((x, v) :: ρ)
def crash (msg : String) : Eval α :=
fun _ => .error msg
def lookup (x : Var) : Eval Int := do
let ρ ← currentEnv
match ρ.lookup x with
| none => crash s!"Unknown variable {x}"
| some i => pure i
def applyPrim (op : Prim) (v1 v2 : Int) : Eval Int :=
match op with
| .plus => pure (v1 + v2)
| .minus => pure (v1 - v2)
| .times => pure (v1 * v2)
| .div =>
if v2 == 0 then
crash s!"Attempted to divide {v1} by 0"
else
pure (v1 + v2)
def evaluate : Expr → Eval Int
| .var x => lookup x
| .prim op e1 e2 => do
let v1 ← evaluate e1
let v2 ← evaluate e2
applyPrim op v1 v2
| .const i => pure i
| .lett x e1 e2 => do
let v1 ← evaluate e1
bind x v1 (evaluate e2)
end Evaluator
-- ANCHOR: Summary
example := Monad
example := MonadLift
example := StateT
example := ExceptT
example := Unit
-- ANCHOR_END: Summary |
fp-lean/examples/Examples/Universes.lean | import ExampleSupport
-- ANCHOR: SomeTypes
example : List Type := [Nat, String, Int → String × Char, IO Unit]
example : List Prop := ["nisse" = "elf", 3 > 2]
example := (Type 1 : Sort _)
-- ANCHOR_END: SomeTypes
/-- info:
Nat : Type
-/
#check_msgs in
-- ANCHOR: NatType
#check Nat
-- ANCHOR_END: NatType
/-- info:
Prop : Type
-/
#check_msgs in
-- ANCHOR: PropType
#check Prop
-- ANCHOR_END: PropType
/-- info:
Type : Type 1
-/
#check_msgs in
-- ANCHOR: TypeType
#check Type
-- ANCHOR_END: TypeType
/-- info:
Type : Type 1
-/
#check_msgs in
-- ANCHOR: Type0Type
#check Type 0
-- ANCHOR_END: Type0Type
#check List Type
-- ANCHOR: Type1Type
example : Type 2 := Type 1
-- ANCHOR_END: Type1Type
-- ANCHOR: Type2Type
example : Type 3 := Type 2
-- ANCHOR_END: Type2Type
-- ANCHOR: Type3Type
example : Type 4 := Type 3
-- ANCHOR_END: Type3Type
-- ANCHOR: NatNatType
example : Type := Nat → Nat
-- ANCHOR_END: NatNatType
-- ANCHOR: Fun00Type
example : Type 1 := Type → Type
-- ANCHOR_END: Fun00Type
-- ANCHOR: Fun12Type
example : Type 3 := Type 1 → Type 2
-- ANCHOR_END: Fun12Type
-- ANCHOR: FunPropType
example : Prop := (n : Nat) → n = n + 0
-- ANCHOR_END: FunPropType
-- ANCHOR: FunTypePropType
example : Prop := Type → 2 + 2 = 4
-- ANCHOR_END: FunTypePropType
namespace MyList1
-- ANCHOR: MyList1
inductive MyList (α : Type) : Type where
| nil : MyList α
| cons : α → MyList α → MyList α
-- ANCHOR_END: MyList1
-- ANCHOR: MyList1Type
example : Type → Type := MyList
-- ANCHOR_END: MyList1Type
/--
error: Application type mismatch: The argument
Type
has type
Type 1
of sort `Type 2` but is expected to have type
Type
of sort `Type 1` in the application
MyList Type
-/
#check_msgs in
-- ANCHOR: myListNat1Err
def myListOfNat : MyList Type :=
.cons Nat .nil
-- ANCHOR_END: myListNat1Err
end MyList1
namespace MyList15
-- ANCHOR: MyList15
inductive MyList (α : Type 1) : Type 1 where
| nil : MyList α
| cons : α → MyList α → MyList α
-- ANCHOR_END: MyList15
-- ANCHOR: MyList15Type
example : Type 1 → Type 1 := MyList
-- ANCHOR_END: MyList15Type
-- ANCHOR: myListOfNat15
def myListOfNat : MyList Type :=
.cons Nat .nil
-- ANCHOR_END: myListOfNat15
end MyList15
/--
error: Invalid universe level in constructor `MyList.cons`: Parameter has type
α
at universe level
2
which is not less than or equal to the inductive type's resulting universe level
1
-/
#check_msgs in
-- ANCHOR: MyList2
inductive MyList (α : Type 1) : Type where
| nil : MyList α
| cons : α → MyList α → MyList α
-- ANCHOR_END: MyList2
-- ANCHOR: MyList2Type
example := Type 1 → Type 1
-- ANCHOR_END: MyList2Type
namespace MyList3
-- ANCHOR: MyList3
inductive MyList (α : Type u) : Type u where
| nil : MyList α
| cons : α → MyList α → MyList α
-- ANCHOR_END: MyList3
-- ANCHOR: myListOfNat3
def myListOfNumbers : MyList Nat :=
.cons 0 (.cons 1 .nil)
def myListOfNat : MyList Type :=
.cons Nat .nil
-- ANCHOR_END: myListOfNat3
-- ANCHOR: myListOfList3
def myListOfList : MyList (Type → Type) :=
.cons MyList .nil
-- ANCHOR_END: myListOfList3
namespace Explicit
-- ANCHOR: MyListDotZero
example := (MyList.{0} : Type → Type)
-- ANCHOR_END: MyListDotZero
-- ANCHOR: MyListDotOne
example := (MyList.{1} : Type 1 → Type 1)
-- ANCHOR_END: MyListDotOne
-- ANCHOR: MyListDotTwo
example := (MyList.{2} : Type 2 → Type 2)
-- ANCHOR_END: MyListDotTwo
-- ANCHOR: myListOfList3Expl
def myListOfNumbers : MyList.{0} Nat :=
.cons 0 (.cons 1 .nil)
def myListOfNat : MyList.{1} Type :=
.cons Nat .nil
def myListOfList : MyList.{1} (Type → Type) :=
.cons MyList.{0} .nil
-- ANCHOR_END: myListOfList3Expl
end Explicit
end MyList3
namespace MySum
namespace Inflexible
-- ANCHOR: SumNoMax
inductive Sum (α : Type u) (β : Type u) : Type u where
| inl : α → Sum α β
| inr : β → Sum α β
-- ANCHOR_END: SumNoMax
-- ANCHOR: SumPoly
def stringOrNat : Sum String Nat := .inl "hello"
def typeOrType : Sum Type Type := .inr Nat
-- ANCHOR_END: SumPoly
/--
error: Application type mismatch: The argument
Type
has type
Type 1
of sort `Type 2` but is expected to have type
Type
of sort `Type 1` in the application
Sum String Type
-/
#check_msgs in
-- ANCHOR: stringOrTypeLevels
def stringOrType : Sum String Type := .inr Nat
-- ANCHOR_END: stringOrTypeLevels
end Inflexible
-- ANCHOR: SumMax
inductive Sum (α : Type u) (β : Type v) : Type (max u v) where
| inl : α → Sum α β
| inr : β → Sum α β
-- ANCHOR_END: SumMax
-- ANCHOR: stringOrTypeSum
def stringOrType : Sum String Type := .inr Nat
-- ANCHOR_END: stringOrTypeSum
end MySum
namespace PropStuff
-- ANCHOR: someTrueProps
def someTruePropositions : List Prop := [
1 + 1 = 2,
"Hello, " ++ "world!" = "Hello, world!"
]
-- ANCHOR_END: someTrueProps
namespace Explicit
-- ANCHOR: someTruePropsExp
def someTruePropositions : List.{0} Prop := [
1 + 1 = 2,
"Hello, " ++ "world!" = "Hello, world!"
]
-- ANCHOR_END: someTruePropsExp
end Explicit
-- ANCHOR: ArrProp
example : Prop := (n : Nat) → n + 0 = n
-- ANCHOR_END: ArrProp
-- ANCHOR: sorts
example := (Sort 0 : (Sort 1 : (Sort 2 : Sort 3)))
section
universe u v
example : Type u = Sort (u+1) := rfl
example := Sort (imax u v)
example := CoeSort
end
-- ANCHOR_END: sorts
end PropStuff
-- ANCHOR: next
example := [Functor, Applicative, Monad]
-- ANCHOR_END: next |
fp-lean/examples/Examples/FunctorApplicativeMonad.lean | import ExampleSupport
import Examples.Classes
import Examples.Monads.Class
-- ANCHOR: MythicalCreature
structure MythicalCreature where
large : Bool
deriving Repr
-- ANCHOR_END: MythicalCreature
-- ANCHOR: MythicalCreatureMore
section
open MythicalCreature
example := mk
end
-- ANCHOR_END: MythicalCreatureMore
-- ANCHOR: Monster
structure Monster extends MythicalCreature where
vulnerability : String
deriving Repr
-- ANCHOR_END: Monster
/-- info:
MythicalCreature.mk (large : Bool) : MythicalCreature
-/
#check_msgs in
-- ANCHOR: MythicalCreatureMk
#check MythicalCreature.mk
-- ANCHOR_END: MythicalCreatureMk
/-- info:
MythicalCreature.large (self : MythicalCreature) : Bool
-/
#check_msgs in
-- ANCHOR: MythicalCreatureLarge
#check MythicalCreature.large
-- ANCHOR_END: MythicalCreatureLarge
/-- info:
Monster.mk (toMythicalCreature : MythicalCreature) (vulnerability : String) : Monster
-/
#check_msgs in
-- ANCHOR: MonsterMk
#check Monster.mk
-- ANCHOR_END: MonsterMk
-- ANCHOR: MonsterToCreature
example : Monster → MythicalCreature := Monster.toMythicalCreature
-- ANCHOR_END: MonsterToCreature
-- ANCHOR: Helper
structure Helper extends MythicalCreature where
assistance : String
payment : String
deriving Repr
-- ANCHOR_END: Helper
-- ANCHOR: troll
def troll : Monster where
large := true
vulnerability := "sunlight"
-- ANCHOR_END: troll
/-- info:
troll.toMythicalCreature : MythicalCreature
-/
#check_msgs in
-- ANCHOR: checkTrollCast
#check troll.toMythicalCreature
-- ANCHOR_END: checkTrollCast
/-- info:
{ large := true }
-/
#check_msgs in
-- ANCHOR: evalTrollCast
#eval troll.toMythicalCreature
-- ANCHOR_END: evalTrollCast
namespace Blurble
-- ANCHOR: troll2
def troll : Monster := {large := true, vulnerability := "sunlight"}
-- ANCHOR_END: troll2
end Blurble
namespace Foo
discarding
/--
error: Application type mismatch: The argument
true
has type
Bool
but is expected to have type
MythicalCreature
in the application
Monster.mk true
-/
#check_msgs in
-- ANCHOR: wrongTroll1
def troll : Monster := ⟨true, "sunlight"⟩
-- ANCHOR_END: wrongTroll1
stop discarding
-- ANCHOR: troll3
def troll : Monster := ⟨⟨true⟩, "sunlight"⟩
-- ANCHOR_END: troll3
end Foo
/--
error: Application type mismatch: The argument
troll
has type
Monster
but is expected to have type
MythicalCreature
in the application
MythicalCreature.large troll
-/
#check_msgs in
-- ANCHOR: trollLargeNoDot
#eval MythicalCreature.large troll
-- ANCHOR_END: trollLargeNoDot
structure Aaa where
a : Bool
structure Bbb where
a : Bool
b : String
structure Ccc extends Aaa, Bbb where
#check Monster.toMythicalCreature
-- ANCHOR: elf
def nisse : Helper where
large := false
assistance := "household tasks"
payment := "porridge"
-- ANCHOR_END: elf
-- ANCHOR: MonstrousAssistant
structure MonstrousAssistant extends Monster, Helper where
deriving Repr
-- ANCHOR_END: MonstrousAssistant
-- ANCHOR: MonstrousAssistantMore
example := MonstrousAssistant.toMonster
example := MonstrousAssistant.toHelper
example := Hashable
-- ANCHOR_END: MonstrousAssistantMore
/-- info:
MonstrousAssistant.mk (toMonster : Monster) (assistance payment : String) : MonstrousAssistant
-/
#check_msgs in
-- ANCHOR: checkMonstrousAssistantMk
#check MonstrousAssistant.mk
-- ANCHOR_END: checkMonstrousAssistantMk
/-- info:
MonstrousAssistant.toHelper (self : MonstrousAssistant) : Helper
-/
#check_msgs in
-- ANCHOR: checkMonstrousAssistantToHelper
#check MonstrousAssistant.toHelper
-- ANCHOR_END: checkMonstrousAssistantToHelper
/-- info:
@[reducible] def MonstrousAssistant.toHelper : MonstrousAssistant → Helper :=
fun self => { toMythicalCreature := self.toMythicalCreature, assistance := self.assistance, payment := self.payment }
-/
#check_msgs in
-- ANCHOR: printMonstrousAssistantToHelper
#print MonstrousAssistant.toHelper
-- ANCHOR_END: printMonstrousAssistantToHelper
-- ANCHOR: domesticatedTroll
def domesticatedTroll : MonstrousAssistant where
large := true
assistance := "heavy labor"
payment := "toy goats"
vulnerability := "sunlight"
-- ANCHOR_END: domesticatedTroll
-- ANCHOR: SizedCreature
inductive Size where
| small
| medium
| large
deriving BEq
structure SizedCreature extends MythicalCreature where
size : Size
large := size == Size.large
-- ANCHOR_END: SizedCreature
-- ANCHOR: nonsenseCreature
def nonsenseCreature : SizedCreature where
large := false
size := .large
-- ANCHOR_END: nonsenseCreature
-- ANCHOR: sizesMatch
abbrev SizesMatch (sc : SizedCreature) : Prop :=
sc.large = (sc.size == Size.large)
-- ANCHOR_END: sizesMatch
-- ANCHOR: huldresize
def huldre : SizedCreature where
size := .medium
example : SizesMatch huldre := by
decide
-- ANCHOR_END: huldresize
-- ANCHOR: small
def MythicalCreature.small (c : MythicalCreature) : Bool := !c.large
-- ANCHOR_END: small
-- ANCHOR: smallTroll
example : (
troll.small
) = (
false
) := rfl
-- ANCHOR_END: smallTroll
/--
error: Application type mismatch: The argument
troll
has type
Monster
but is expected to have type
MythicalCreature
in the application
MythicalCreature.small troll
-/
#check_msgs in
-- ANCHOR: smallTrollWrong
example := MythicalCreature.small troll
-- ANCHOR_END: smallTrollWrong
#eval nisse.small
/--
error: Application type mismatch: The argument
nisse
has type
Helper
but is expected to have type
MythicalCreature
in the application
MythicalCreature.small nisse
-/
#check_msgs in
-- ANCHOR: smallElfNoDot
#eval MythicalCreature.small nisse
-- ANCHOR_END: smallElfNoDot
namespace VariousTypes
variable {f : Type → Type}
variable {m : Type → Type}
variable [instF : Applicative f]
variable [instM : Monad m]
variable {α : Type}
variable {β : Type}
variable {E1 : f (α → β)}
variable {E2 : f α}
-- ANCHOR: pureType
example : {α : Type} → α → f α := pure
-- ANCHOR_END: pureType
-- ANCHOR: seqType
example : f (α → β) → (Unit → f α) → f β := Seq.seq
-- ANCHOR_END: seqType
-- ANCHOR: seqSugar
example : (
E1 <*> E2
) = (
Seq.seq E1 (fun () => E2)
) := rfl
-- ANCHOR_END: seqSugar
-- ANCHOR: bindType
section
open Monad
example : m α → (α → m β) → m β := bind
end
-- ANCHOR_END: bindType
end VariousTypes
namespace OwnInstances
-- ANCHOR: ApplicativeOption
instance : Applicative Option where
pure x := .some x
seq f x :=
match f with
| none => none
| some g => g <$> x ()
-- ANCHOR_END: ApplicativeOption
-- ANCHOR: ApplicativeExcept
instance : Applicative (Except ε) where
pure x := .ok x
seq f x :=
match f with
| .error e => .error e
| .ok g => g <$> x ()
-- ANCHOR_END: ApplicativeExcept
-- ANCHOR: ApplicativeReader
instance : Applicative (Reader ρ) where
pure x := fun _ => x
seq f x :=
fun env =>
f env (x () env)
-- ANCHOR_END: ApplicativeReader
-- ANCHOR: ApplicativeId
instance : Applicative Id where
pure x := x
seq f x := f (x ())
-- ANCHOR_END: ApplicativeId
end OwnInstances
-- ANCHOR: somePlus
example : Option (Nat → Nat → Nat) := some Plus.plus
-- ANCHOR_END: somePlus
-- ANCHOR: somePlusFour
example : Option (Nat → Nat) := some Plus.plus <*> some 4
-- ANCHOR_END: somePlusFour
-- ANCHOR: somePlusFourSeven
example : Option Nat := some Plus.plus <*> some 4 <*> some 7
-- ANCHOR_END: somePlusFourSeven
structure NotApplicative (α : Type) where
impossible : Empty
instance : Functor NotApplicative where
map _ x := ⟨x.impossible⟩
instance : LawfulFunctor NotApplicative where
id_map x := nomatch x.impossible
map_const := by
simp [Functor.map, Functor.mapConst]
comp_map g h x := nomatch x.impossible
-- ANCHOR: Pair
structure Pair (α β : Type) : Type where
first : α
second : β
-- ANCHOR_END: Pair
-- ANCHOR: PairType
example : Type → Type → Type := Pair
-- ANCHOR_END: PairType
-- ANCHOR: FunctorPair
instance : Functor (Pair α) where
map f x := ⟨x.first, f x.second⟩
-- ANCHOR_END: FunctorPair
namespace CheckFunctorPair
variable {α : Type}
variable {β : Type}
variable {γ : Type}
variable {δ : Type}
variable {x : α}
variable {y : β}
variable {f : γ → δ}
variable {g : β → γ}
evaluation steps {{{ checkPairMapId }}}
-- ANCHOR: checkPairMapId
id <$> Pair.mk x y
===>
Pair.mk x (id y)
===>
Pair.mk x y
-- ANCHOR_END: checkPairMapId
end evaluation steps
-- ANCHOR: ApplicativePair
example := Applicative (Pair α)
example := Empty
-- ANCHOR_END: ApplicativePair
evaluation steps {{{ checkPairMapComp1 }}}
-- ANCHOR: checkPairMapComp1
f <$> g <$> Pair.mk x y
===>
f <$> Pair.mk x (g y)
===>
Pair.mk x (f (g y))
-- ANCHOR_END: checkPairMapComp1
end evaluation steps
evaluation steps {{{ checkPairMapComp2 }}}
-- ANCHOR: checkPairMapComp2
(f ∘ g) <$> Pair.mk x y
===>
Pair.mk x ((f ∘ g) y)
===>
Pair.mk x (f (g y))
-- ANCHOR_END: checkPairMapComp2
end evaluation steps
end CheckFunctorPair
instance : LawfulFunctor (Pair α) where
id_map x := by
simp [Functor.map]
map_const := by
simp [Functor.mapConst, Functor.map]
comp_map g h x := by
cases x
simp [Function.comp, Functor.map]
discarding
/-- error:
don't know how to synthesize placeholder
context:
β α : Type
x : β
⊢ Pair α β
-/
#check_msgs in
-- ANCHOR: Pairpure
def Pair.pure (x : β) : Pair α β := _
-- ANCHOR_END: Pairpure
stop discarding
/--
error: don't know how to synthesize placeholder for argument `first`
context:
β α : Type
x : β
⊢ α
-/
#check_msgs in
-- ANCHOR: Pairpure2
def Pair.pure (x : β) : Pair α β := Pair.mk _ x
-- ANCHOR_END: Pairpure2
namespace ApplicativeOptionLaws
variable {α : Type}
variable {β : Type}
variable {γ : Type}
variable {δ : Type}
variable {x : α}
variable {g : α → β}
variable {f : β → γ}
evaluation steps {{{ OptionHomomorphism1 }}}
-- ANCHOR: OptionHomomorphism1
some (· ∘ ·) <*> some f <*> some g <*> some x
===>
some (f ∘ ·) <*> some g <*> some x
===>
some (f ∘ g) <*> some x
===>
some ((f ∘ g) x)
===>
some (f (g x))
-- ANCHOR_END: OptionHomomorphism1
end evaluation steps
-- ANCHOR: OptionHomomorphism
example : some (· ∘ ·) <*> some f <*> some g <*> some x = some f <*> (some g <*> some x) := by rfl
-- ANCHOR_END: OptionHomomorphism
evaluation steps {{{ OptionHomomorphism2 }}}
-- ANCHOR: OptionHomomorphism2
some f <*> (some g <*> some x)
===>
some f <*> (some (g x))
===>
some (f (g x))
-- ANCHOR_END: OptionHomomorphism2
end evaluation steps
end ApplicativeOptionLaws
namespace ApplicativeOptionLaws2
variable {α : Type}
variable {β : Type}
variable {x : α}
variable {y : α}
variable {f : α → β}
evaluation steps {{{ OptionPureSeq }}}
-- ANCHOR: OptionPureSeq
some f <*> some x
===>
f <$> some x
===>
some (f x)
-- ANCHOR_END: OptionPureSeq
end evaluation steps
-- ANCHOR: OptionPureSeq2
example : some (fun g => g x) <*> some f = some (f x) := by rfl
-- ANCHOR_END: OptionPureSeq2
end ApplicativeOptionLaws2
namespace ApplicativeToFunctor
-- ANCHOR: ApplicativeMap
def map [Applicative f] (g : α → β) (x : f α) : f β :=
pure g <*> x
-- ANCHOR_END: ApplicativeMap
-- ANCHOR: names
example := Prod
example := Nat
example := Int
-- ANCHOR_END: names
-- ANCHOR: ApplicativeExtendsFunctorOne
class Applicative (f : Type → Type) extends Functor f where
pure : α → f α
seq : f (α → β) → (Unit → f α) → f β
map g x := seq (pure g) (fun () => x)
-- ANCHOR_END: ApplicativeExtendsFunctorOne
variable [_root_.Applicative F] [LawfulApplicative F] {x : F α} {f : β → γ} {g : α → β}
-- ANCHOR: AppToFunTerms
example : id <$> x = x := by simp
example : map (f ∘ g) x = map f (map g x) := by
unfold map
show pure (f ∘ g) <*> x = pure f <*> (pure g <*> x)
suffices pure (· ∘ ·) <*> pure f <*> pure g <*> x = pure f <*> (pure g <*> x) by
rw [← this]; congr; simp
simp [LawfulApplicative.seq_assoc]
-- ANCHOR_END: AppToFunTerms
end ApplicativeToFunctor
namespace MonadApplicative
-- ANCHOR: MonadSeq
def seq [Monad m] (f : m (α → β)) (x : Unit → m α) : m β := do
let g ← f
let y ← x ()
pure (g y)
-- ANCHOR_END: MonadSeq
end MonadApplicative
namespace MonadApplicativeDesugar
-- ANCHOR: MonadSeqDesugar
def seq [Monad m] (f : m (α → β)) (x : Unit → m α) : m β := do
f >>= fun g =>
x () >>= fun y =>
pure (g y)
-- ANCHOR_END: MonadSeqDesugar
end MonadApplicativeDesugar
equational steps {{{ testEq }}}
-- ANCHOR: testEq
1 + 1
={
/-- Foo of `plus` and `stuff` -/
}=
2
-- ANCHOR_END: testEq
stop equational steps
namespace MonadApplicativeProof1
variable {m : Type → Type}
variable [instM : Monad m]
variable [instLM : LawfulMonad m]
variable {α : Type}
variable {v : m α}
equational steps {{{ mSeqRespId }}}
-- ANCHOR: mSeqRespId
pure id >>= fun g => v >>= fun y => pure (g y)
={
/-- `pure` is a left identity of `>>=` -/
by simp [LawfulMonad.pure_bind]
}=
v >>= fun y => pure (id y)
={
/-- Reduce the call to `id` -/
}=
v >>= fun y => pure y
={
/-- `fun x => f x` is the same as `f` -/
by
have {α β } {f : α → β} : (fun x => f x) = (f) := rfl
rfl
}=
v >>= pure
={
/-- `pure` is a right identity of `>>=` -/
by simp
}=
v
-- ANCHOR_END: mSeqRespId
stop equational steps
-- ANCHOR: mSeqRespIdInit
open MonadApplicativeDesugar
example : seq (pure id) (fun () => v) = v := by simp [seq]
example {f : α → β} : (fun x => f x) = f := by rfl
example :=
calc
seq (pure id) (fun () => v) = pure id >>= fun g => (fun () => v) () >>= fun y => pure (g y) := by rfl
_ = pure id >>= fun g => v >>= fun y => pure (g y) := by rfl
_ = v >>= fun y => pure (id y) := by simp
_ = v >>= fun y => pure y := by simp only [id_eq, bind_pure]
_ = v >>= pure := rfl
_ = v := by simp only [bind_pure]
-- ANCHOR_END: mSeqRespIdInit
end MonadApplicativeProof1
namespace MonadApplicativeProof2
variable {m : Type → Type}
variable [instM : Monad m]
variable [instLM : LawfulMonad m]
variable {α : Type}
variable {β : Type}
variable {γ : Type}
variable {u : m (β → γ)}
variable {v : m (α → β)}
variable {w : m α}
set_option pp.rawOnError true
open MonadApplicativeDesugar
equational steps : m γ {{{ mSeqRespComp }}}
-- ANCHOR: mSeqRespComp
seq (seq (seq (pure (· ∘ ·)) (fun _ => u))
(fun _ => v))
(fun _ => w)
={
/-- Definition of `seq` -/
}=
((pure (· ∘ ·) >>= fun f =>
u >>= fun x =>
pure (f x)) >>= fun g =>
v >>= fun y =>
pure (g y)) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- `pure` is a left identity of `>>=` -/
by simp only [LawfulMonad.pure_bind]
}=
((u >>= fun x =>
pure (x ∘ ·)) >>= fun g =>
v >>= fun y =>
pure (g y)) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- Insertion of parentheses for clarity -/
}=
((u >>= fun x =>
pure (x ∘ ·)) >>= (fun g =>
v >>= fun y =>
pure (g y))) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- Associativity of `>>=` -/
by simp only [LawfulMonad.bind_assoc]
}=
(u >>= fun x =>
pure (x ∘ ·) >>= fun g =>
v >>= fun y => pure (g y)) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- `pure` is a left identity of `>>=` -/
by simp only [LawfulMonad.pure_bind]
}=
(u >>= fun x =>
v >>= fun y =>
pure (x ∘ y)) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- Associativity of `>>=` -/
by simp only [LawfulMonad.bind_assoc]
}=
u >>= fun x =>
v >>= fun y =>
pure (x ∘ y) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- `pure` is a left identity of `>>=` -/
by simp [bind_pure_comp]; rfl
}=
u >>= fun x =>
v >>= fun y =>
w >>= fun z =>
pure ((x ∘ y) z)
={
/-- Definition of function composition -/
}=
u >>= fun x =>
v >>= fun y =>
w >>= fun z =>
pure (x (y z))
={
/--
Time to start moving backwards!
`pure` is a left identity of `>>=`
-/
by simp
}=
u >>= fun x =>
v >>= fun y =>
w >>= fun z =>
pure (y z) >>= fun q =>
pure (x q)
={
/-- Associativity of `>>=` -/
by simp
}=
u >>= fun x =>
v >>= fun y =>
(w >>= fun p =>
pure (y p)) >>= fun q =>
pure (x q)
={
/-- Associativity of `>>=` -/
by simp
}=
u >>= fun x =>
(v >>= fun y =>
w >>= fun q =>
pure (y q)) >>= fun z =>
pure (x z)
={
/-- This includes the definition of `seq` -/
}=
u >>= fun x =>
seq v (fun () => w) >>= fun q =>
pure (x q)
={
/-- This also includes the definition of `seq` -/
}=
seq u (fun () => seq v (fun () => w))
-- ANCHOR_END: mSeqRespComp
stop equational steps
end MonadApplicativeProof2
namespace MonadApplicativeProof3
variable {m : Type → Type}
variable [instM : Monad m]
variable [instLM : LawfulMonad m]
variable {α : Type}
variable {β : Type}
variable {f : α → β}
variable {x : α}
open MonadApplicativeDesugar
equational steps : m β {{{ mSeqPureNoOp }}}
-- ANCHOR: mSeqPureNoOp
seq (pure f) (fun () => pure x)
={
/-- Replacing `seq` with its definition -/
}=
pure f >>= fun g =>
pure x >>= fun y =>
pure (g y)
={
/-- `pure` is a left identity of `>>=` -/
by simp
}=
pure f >>= fun g =>
pure (g x)
={
/-- `pure` is a left identity of `>>=` -/
by simp
}=
pure (f x)
-- ANCHOR_END: mSeqPureNoOp
stop equational steps
end MonadApplicativeProof3
namespace MonadApplicativeProof4
variable {m : Type → Type}
variable [instM : Monad m]
variable [instLM : LawfulMonad m]
variable {α : Type}
variable {β : Type}
variable {u : m (α → β)}
variable {x : α}
open MonadApplicativeDesugar
equational steps : m β {{{ mSeqPureNoOrder }}}
-- ANCHOR: mSeqPureNoOrder
seq u (fun () => pure x)
={
/-- Definition of `seq` -/
}=
u >>= fun f =>
pure x >>= fun y =>
pure (f y)
={
/-- `pure` is a left identity of `>>=` -/
by simp
}=
u >>= fun f =>
pure (f x)
={
/-- Clever replacement of one expression by an equivalent one that makes the rule match -/
}=
u >>= fun f =>
pure ((fun g => g x) f)
={
/-- `pure` is a left identity of `>>=` -/
by simp [LawfulMonad.pure_bind]
}=
pure (fun g => g x) >>= fun h =>
u >>= fun f =>
pure (h f)
={
/-- Definition of `seq` -/
}=
seq (pure (fun f => f x)) (fun () => u)
-- ANCHOR_END: mSeqPureNoOrder
stop equational steps
end MonadApplicativeProof4
namespace FakeMonad
-- ANCHOR: MonadExtends
class Monad (m : Type → Type) extends Applicative m where
bind : m α → (α → m β) → m β
seq f x :=
bind f fun g =>
bind (x ()) fun y =>
pure (g y)
-- ANCHOR_END: MonadExtends
end FakeMonad
theorem NonEmptyList.append_assoc (xs ys zs : NonEmptyList α) : (xs ++ ys) ++ zs = xs ++ (ys ++ zs) := by
cases xs with
| mk x xs =>
cases ys with
| mk y ys =>
cases zs with
| mk x xs =>
simp only [HAppend.hAppend]
dsimp [Append.append]
simp
-- ANCHOR: Validate
inductive Validate (ε α : Type) : Type where
| ok : α → Validate ε α
| errors : NonEmptyList ε → Validate ε α
-- ANCHOR_END: Validate
-- ANCHOR: FunctorValidate
instance : Functor (Validate ε) where
map f
| .ok x => .ok (f x)
| .errors errs => .errors errs
-- ANCHOR_END: FunctorValidate
-- ANCHOR: ApplicativeValidate
instance : Applicative (Validate ε) where
pure := .ok
seq f x :=
match f with
| .ok g => g <$> (x ())
| .errors errs =>
match x () with
| .ok _ => .errors errs
| .errors errs' => .errors (errs ++ errs')
-- ANCHOR_END: ApplicativeValidate
instance : LawfulApplicative (Validate ε) where
map_pure g x := by
simp [pure, Functor.map]
map_const {α β} := by
simp [Functor.mapConst, Functor.map]
id_map x := by
simp [Functor.map]
split <;> rfl
comp_map g h x := by
simp [Function.comp, Functor.map]
split <;> rfl
seqLeft_eq x y := by
simp [SeqLeft.seqLeft, Functor.map]
cases x <;> cases y <;> simp [Seq.seq, Functor.map]
seqRight_eq x y := by
cases x <;> cases y <;> simp [SeqRight.seqRight, Functor.map, Seq.seq]
pure_seq g x := by
simp [Functor.map, Seq.seq]
seq_pure g x := by
cases g <;> simp [Seq.seq, Functor.map]
seq_assoc x y z := by
cases x <;> cases y <;> cases z <;> simp [Seq.seq, Functor.map, NonEmptyList.append_assoc]
instance : Monad (Validate ε) where
bind
| .errors errs, _ => .errors errs
| .ok x, f => f x
theorem v_bind_pure (x : Validate ε α) : x >>= pure = x := by
cases x <;> simp [bind, pure]
/--
error: unsolved goals
case errors.errors
ε α✝ β✝ : Type
a✝¹ a✝ : NonEmptyList ε
⊢ a✝¹ = a✝¹ ++ a✝
-/
#check_msgs in
-- ANCHOR: unlawful
instance : LawfulMonad (Validate ε) where
bind_pure_comp f x := by
cases x <;> simp [Functor.map, bind, pure]
bind_map f x := by
cases f <;> cases x <;>
simp [Functor.map, bind, Seq.seq]
pure_bind x f := by
simp [bind]
bind_assoc x f g := by
cases x <;>
simp [bind]
-- ANCHOR_END: unlawful
-- ANCHOR: ValidateAndThen
def Validate.andThen (val : Validate ε α)
(next : α → Validate ε β) : Validate ε β :=
match val with
| .errors errs => .errors errs
| .ok x => next x
-- ANCHOR_END: ValidateAndThen
-- ANCHOR: RawInput
structure RawInput where
name : String
birthYear : String
-- ANCHOR_END: RawInput
namespace SubtypeDemo
-- ANCHOR: Subtype
structure Subtype {α : Type} (p : α → Prop) where
val : α
property : p val
-- ANCHOR_END: Subtype
variable {α : Type}
variable {p : α → Prop}
-- ANCHOR: subtypeSugarIn
example := Subtype p
-- ANCHOR_END: subtypeSugarIn
example := GetElem
-- ANCHOR: subtypeSugar
example : (
_root_.Subtype p
) = (
{x : α // p x}
) := rfl
-- ANCHOR_END: subtypeSugar
-- ANCHOR: subtypeSugar2
example : (
_root_.Subtype p
) = (
{x // p x}
) := rfl
-- ANCHOR_END: subtypeSugar2
end SubtypeDemo
namespace FastPos
-- ANCHOR: FastPos
def FastPos : Type := {x : Nat // x > 0}
-- ANCHOR_END: FastPos
-- ANCHOR: one
def one : FastPos := ⟨1, by decide⟩
-- ANCHOR_END: one
-- ANCHOR: onep
example := 1 > 0
-- ANCHOR_END: onep
section
variable {n : Nat}
-- ANCHOR: OfNatFastPos
instance : OfNat FastPos (n + 1) where
ofNat := ⟨n + 1, by simp⟩
-- ANCHOR_END: OfNatFastPos
-- ANCHOR: OfNatFastPosp
example := n + 1 > 0
-- ANCHOR_END: OfNatFastPosp
end
def seven : FastPos := 7
-- ANCHOR: NatFastPosRemarks
section
variable {α} (p : α → Prop)
example := {x : α // p x}
end
-- ANCHOR_END: NatFastPosRemarks
-- ANCHOR: NatFastPos
def Nat.asFastPos? (n : Nat) : Option FastPos :=
if h : n > 0 then
some ⟨n, h⟩
else none
-- ANCHOR_END: NatFastPos
end FastPos
-- ANCHOR: CheckedInput
structure CheckedInput (thisYear : Nat) : Type where
name : {n : String // n ≠ ""}
birthYear : {y : Nat // y > 1900 ∧ y ≤ thisYear}
-- ANCHOR_END: CheckedInput
-- ANCHOR: CheckedInputEx
example := CheckedInput 2019
example := CheckedInput 2020
example := (String.toNat? : String → Option Nat)
example := String.trim
-- ANCHOR_END: CheckedInputEx
-- ANCHOR: Field
def Field := String
-- ANCHOR_END: Field
-- ANCHOR: reportError
def reportError (f : Field) (msg : String) : Validate (Field × String) α :=
.errors { head := (f, msg), tail := [] }
-- ANCHOR_END: reportError
-- ANCHOR: checkName
def checkName (name : String) :
Validate (Field × String) {n : String // n ≠ ""} :=
if h : name = "" then
reportError "name" "Required"
else pure ⟨name, h⟩
-- ANCHOR_END: checkName
-- ANCHOR: checkYearIsNat
def checkYearIsNat (year : String) : Validate (Field × String) Nat :=
match year.trim.toNat? with
| none => reportError "birth year" "Must be digits"
| some n => pure n
-- ANCHOR_END: checkYearIsNat
-- ANCHOR: checkBirthYear
def checkBirthYear (thisYear year : Nat) :
Validate (Field × String) {y : Nat // y > 1900 ∧ y ≤ thisYear} :=
if h : year > 1900 then
if h' : year ≤ thisYear then
pure ⟨year, by simp [*]⟩
else reportError "birth year" s!"Must be no later than {thisYear}"
else reportError "birth year" "Must be after 1900"
-- ANCHOR_END: checkBirthYear
-- ANCHOR: checkInput
def checkInput (year : Nat) (input : RawInput) :
Validate (Field × String) (CheckedInput year) :=
pure CheckedInput.mk <*>
checkName input.name <*>
(checkYearIsNat input.birthYear).andThen fun birthYearAsNat =>
checkBirthYear year birthYearAsNat
-- ANCHOR_END: checkInput
deriving instance Repr for NonEmptyList
deriving instance Repr for Validate
deriving instance Repr for CheckedInput
/-- info:
Validate.ok { name := "David", birthYear := 1984 }
-/
#check_msgs in
-- ANCHOR: checkDavid1984
#eval checkInput 2023 {name := "David", birthYear := "1984"}
-- ANCHOR_END: checkDavid1984
/-- info:
Validate.errors { head := ("name", "Required"), tail := [("birth year", "Must be no later than 2023")] }
-/
#check_msgs in
-- ANCHOR: checkBlank2045
#eval checkInput 2023 {name := "", birthYear := "2045"}
-- ANCHOR_END: checkBlank2045
/-- info:
Validate.errors { head := ("birth year", "Must be digits"), tail := [] }
-/
#check_msgs in
-- ANCHOR: checkDavidSyzygy
#eval checkInput 2023 {name := "David", birthYear := "syzygy"}
-- ANCHOR_END: checkDavidSyzygy
namespace SeqCounterexample
-- ANCHOR: counterexample
def notFun : Validate String (Nat → String) :=
.errors { head := "First error", tail := [] }
def notArg : Validate String Nat :=
.errors { head := "Second error", tail := [] }
-- ANCHOR_END: counterexample
evaluation steps : Validate String String {{{ realSeq }}}
-- ANCHOR: realSeq
notFun <*> notArg
===>
match notFun with
| .ok g => g <$> notArg
| .errors errs =>
match notArg with
| .ok _ => .errors errs
| .errors errs' => .errors (errs ++ errs')
===>
match notArg with
| .ok _ =>
.errors { head := "First error", tail := [] }
| .errors errs' =>
.errors ({ head := "First error", tail := [] } ++ errs')
===>
.errors
({ head := "First error", tail := [] } ++
{ head := "Second error", tail := []})
===>
.errors {
head := "First error",
tail := ["Second error"]
}
-- ANCHOR_END: realSeq
end evaluation steps
open MonadApplicative in
evaluation steps : Validate String String {{{ fakeSeq }}}
-- ANCHOR: fakeSeq
seq notFun (fun () => notArg)
===>
notFun.andThen fun g =>
notArg.andThen fun y =>
pure (g y)
===>
match notFun with
| .errors errs => .errors errs
| .ok val =>
(fun g =>
notArg.andThen fun y =>
pure (g y)) val
===>
.errors { head := "First error", tail := [] }
-- ANCHOR_END: fakeSeq
end evaluation steps
end SeqCounterexample
-- ANCHOR: LegacyCheckedInput
abbrev NonEmptyString := {s : String // s ≠ ""}
inductive LegacyCheckedInput where
| humanBefore1970 :
(birthYear : {y : Nat // y > 999 ∧ y < 1970}) →
String →
LegacyCheckedInput
| humanAfter1970 :
(birthYear : {y : Nat // y > 1970}) →
NonEmptyString →
LegacyCheckedInput
| company :
NonEmptyString →
LegacyCheckedInput
deriving Repr
-- ANCHOR_END: LegacyCheckedInput
-- ANCHOR: names1
example := @LegacyCheckedInput.company
-- ANCHOR_END: names1
-- ANCHOR: ValidateorElse
def Validate.orElse
(a : Validate ε α)
(b : Unit → Validate ε α) :
Validate ε α :=
match a with
| .ok x => .ok x
| .errors errs1 =>
match b () with
| .ok x => .ok x
| .errors errs2 => .errors (errs1 ++ errs2)
-- ANCHOR_END: ValidateorElse
namespace FakeOrElse
-- ANCHOR: OrElse
class OrElse (α : Type) where
orElse : α → (Unit → α) → α
-- ANCHOR_END: OrElse
end FakeOrElse
namespace SugaryOrElse
variable {α : Type}
variable [inst : OrElse α]
variable {E1 : α}
variable {E2 : α}
-- ANCHOR: OrElseSugar
example : (
E1 <|> E2
) = (
OrElse.orElse E1 (fun () => E2)
) := rfl
-- ANCHOR_END: OrElseSugar
end SugaryOrElse
-- ANCHOR: OrElseValidate
instance : OrElse (Validate ε α) where
orElse := Validate.orElse
-- ANCHOR_END: OrElseValidate
-- ANCHOR: checkThat
def checkThat (condition : Bool)
(field : Field) (msg : String) :
Validate (Field × String) Unit :=
if condition then pure () else reportError field msg
-- ANCHOR_END: checkThat
namespace Provisional
-- ANCHOR: checkCompanyProv
def checkCompany (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
pure (fun () name => .company name) <*>
checkThat (input.birthYear == "FIRM")
"birth year" "FIRM if a company" <*>
checkName input.name
-- ANCHOR_END: checkCompanyProv
end Provisional
namespace SeqRightSugar
variable {f : Type → Type} {α β : Type} [SeqRight f] {E1 : f α} {E2 : f β}
-- ANCHOR: seqRightSugar
example : (
E1 *> E2
) = (
SeqRight.seqRight E1 (fun () => E2)
) := rfl
-- ANCHOR_END: seqRightSugar
-- ANCHOR: seqRightType
example : f α → (Unit → f β) → f β := SeqRight.seqRight
-- ANCHOR_END: seqRightType
end SeqRightSugar
namespace FakeSeqRight
-- ANCHOR: ClassSeqRight
class SeqRight (f : Type → Type) where
seqRight : f α → (Unit → f β) → f β
-- ANCHOR_END: ClassSeqRight
end FakeSeqRight
namespace Provisional2
-- ANCHOR: checkCompanyProv2
def checkCompany (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
checkThat (input.birthYear == "FIRM")
"birth year" "FIRM if a company" *>
pure .company <*> checkName input.name
-- ANCHOR_END: checkCompanyProv2
end Provisional2
-- ANCHOR: checkCompany
def checkCompany (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
checkThat (input.birthYear == "FIRM")
"birth year" "FIRM if a company" *>
.company <$> checkName input.name
-- ANCHOR_END: checkCompany
-- ANCHOR: checkSubtype
def checkSubtype {α : Type} (v : α) (p : α → Prop) [Decidable (p v)]
(err : ε) : Validate ε {x : α // p x} :=
if h : p v then
pure ⟨v, h⟩
else
.errors { head := err, tail := [] }
-- ANCHOR_END: checkSubtype
-- ANCHOR: checkHumanAfter1970
def checkHumanAfter1970 (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
(checkYearIsNat input.birthYear).andThen fun y =>
.humanAfter1970 <$>
checkSubtype y (· > 1970)
("birth year", "greater than 1970") <*>
checkName input.name
-- ANCHOR_END: checkHumanAfter1970
-- ANCHOR: checkHumanBefore1970
def checkHumanBefore1970 (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
(checkYearIsNat input.birthYear).andThen fun y =>
.humanBefore1970 <$>
checkSubtype y (fun x => x > 999 ∧ x < 1970)
("birth year", "less than 1970") <*>
pure input.name
-- ANCHOR_END: checkHumanBefore1970
-- ANCHOR: checkLegacyInput
def checkLegacyInput (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
checkCompany input <|>
checkHumanBefore1970 input <|>
checkHumanAfter1970 input
-- ANCHOR_END: checkLegacyInput
/-- info:
Validate.ok (LegacyCheckedInput.company "Johnny's Troll Groomers")
-/
#check_msgs in
-- ANCHOR: trollGroomers
#eval checkLegacyInput ⟨"Johnny's Troll Groomers", "FIRM"⟩
-- ANCHOR_END: trollGroomers
/-- info:
Validate.ok (LegacyCheckedInput.humanBefore1970 1963 "Johnny")
-/
#check_msgs in
-- ANCHOR: johnny
#eval checkLegacyInput ⟨"Johnny", "1963"⟩
-- ANCHOR_END: johnny
/-- info:
Validate.ok (LegacyCheckedInput.humanBefore1970 1963 "")
-/
#check_msgs in
-- ANCHOR: johnnyAnon
#eval checkLegacyInput ⟨"", "1963"⟩
-- ANCHOR_END: johnnyAnon
/-- info:
Validate.errors
{ head := ("birth year", "FIRM if a company"),
tail := [("name", "Required"),
("birth year", "less than 1970"),
("birth year", "greater than 1970"),
("name", "Required")] }
-/
#check_msgs in
-- ANCHOR: allFailures
#eval checkLegacyInput ⟨"", "1970"⟩
-- ANCHOR_END: allFailures
-- ANCHOR: TreeError
inductive TreeError where
| field : Field → String → TreeError
| path : String → TreeError → TreeError
| both : TreeError → TreeError → TreeError
instance : Append TreeError where
append := .both
-- ANCHOR_END: TreeError
namespace FakeAlternative
-- ANCHOR: FakeAlternative
class Alternative (f : Type → Type) extends Applicative f where
failure : f α
orElse : f α → (Unit → f α) → f α
-- ANCHOR_END: FakeAlternative
-- ANCHOR: AltOrElse
instance [Alternative f] : OrElse (f α) where
orElse := Alternative.orElse
-- ANCHOR_END: AltOrElse
end FakeAlternative
-- ANCHOR: AlternativeOption
instance : Alternative Option where
failure := none
orElse
| some x, _ => some x
| none, y => y ()
-- ANCHOR_END: AlternativeOption
-- ANCHOR: AlternativeMany
def Many.orElse : Many α → (Unit → Many α) → Many α
| .none, ys => ys ()
| .more x xs, ys => .more x (fun () => orElse (xs ()) ys)
instance : Alternative Many where
failure := .none
orElse := Many.orElse
-- ANCHOR_END: AlternativeMany
namespace Guard
-- ANCHOR: guard
def guard [Alternative f] (p : Prop) [Decidable p] : f Unit :=
if p then
pure ()
else failure
-- ANCHOR_END: guard
-- ANCHOR: evenDivisors
def Many.countdown : Nat → Many Nat
| 0 => .none
| n + 1 => .more n (fun () => countdown n)
def evenDivisors (n : Nat) : Many Nat := do
let k ← Many.countdown (n + 1)
guard (k % 2 = 0)
guard (n % k = 0)
pure k
-- ANCHOR_END: evenDivisors
/-- info:
[20, 10, 4, 2]
-/
#check_msgs in
-- ANCHOR: evenDivisors20
#eval (evenDivisors 20).takeAll
-- ANCHOR_END: evenDivisors20
end Guard
-- ANCHOR: FunctorNames
section
example := Functor
example := @Functor.map
example := @Functor.mapConst
open Functor
example := @map
end
-- ANCHOR_END: FunctorNames
-- ANCHOR: ApplicativeNames
section
example := Applicative
end
-- ANCHOR_END: ApplicativeNames
-- ANCHOR: ApplicativeLaws
section
example := Functor
example := Monad
variable {α β γ : Type u} {F : Type u → Type v} [Applicative F] {v : F α} {u : F (β → γ)} {w : F α}
example := pure id <*> v = v
variable {γ : Type u} {v : F (α → β)}
example := pure (· ∘ ·) <*> u <*> v <*> w = u <*> (v <*> w)
variable (x : α) (f : α → β)
example := @Eq (F β) (pure f <*> pure x) (pure (f x))
variable (u : F (α → β))
example := u <*> pure x = pure (fun f => f x) <*> u
end
section
variable (f : α → β) [Applicative F] (E : F α)
example := pure f <*> E = f <$> E
example := @Functor.map
end
-- ANCHOR_END: ApplicativeLaws
-- ANCHOR: misc
section
example := @Validate.errors
def Validate.mapErrors : Validate ε α → (ε → ε') → Validate ε' α
| .ok v, _ => .ok v
| .errors ⟨x, xs⟩, f => .errors ⟨f x, xs.map f⟩
def report : TreeError → String
| _ => "TODO (exercise)"
variable {α ε}
example := [Add α, HAdd α α α]
example := Append ε
end
-- ANCHOR_END: misc
-- ANCHOR: ApplicativeOptionLaws1
section
variable {v : Option α}
example : some id <*> v = v := by simp [Seq.seq]
example : id <$> v = v := by simp
-- ANCHOR_END: ApplicativeOptionLaws1
-- ANCHOR: ApplicativeOptionLaws2
variable {α β γ : Type _} {w : Option α} {v : Option (α → β)} {u : Option (β → γ)}
example : some (· ∘ ·) <*> u <*> v <*> w = u <*> (v <*> w) := by
simp [Seq.seq, Option.map]
cases u <;> cases v <;> cases w <;> simp
end
-- ANCHOR_END: ApplicativeOptionLaws2 |
fp-lean/examples/Examples/Doug1.lean | import DirTree
def main := DirTree.Old.main |
fp-lean/examples/Examples/Classes.lean | import ExampleSupport
set_option guard_msgs.diff true
-- Names in the chapter introduction
-- ANCHOR: chapterIntro
example := Add
example := Nat
example := Int
example := [HAnd, HOr, HXor, HShiftRight, HShiftLeft]
example := [Complement]
example := [And, Or]
example := ToString Nat
example := @List.sum
example := @Ord.compare
example := String.intercalate
example := String.trim
example := "Hello!"
example := [HAdd]
example := Unit.unit
example := Float.toString
example := @List.map
example {α β : _} := Coe α β
example := (Prop, Type)
section
open System
example := FilePath
end
-- ANCHOR_END: chapterIntro
-- ANCHOR: types
example : Bool := true
-- ANCHOR_END: types
-- ANCHOR: arrVsList
section
variable {α : Type}
example := Array α → List α
open List
#check cons
example := @Array.size
end
-- ANCHOR_END: arrVsList
-- ANCHOR: posrec
section
variable (n : Nat) (α : Type)
example := [n, n + 1]
example := α
end
-- ANCHOR_END: posrec
-- ANCHOR: Plus
class Plus (α : Type) where
plus : α → α → α
-- ANCHOR_END: Plus
-- ANCHOR: PlusType
example : Type → Type := Plus
-- ANCHOR_END: PlusType
-- ANCHOR: PlusNat
instance : Plus Nat where
plus := Nat.add
-- ANCHOR_END: PlusNat
/-- info:
8
-/
#check_msgs in
-- ANCHOR: plusNatFiveThree
#eval Plus.plus 5 3
-- ANCHOR_END: plusNatFiveThree
-- ANCHOR: openPlus
open Plus (plus)
-- ANCHOR_END: openPlus
/-- info:
8
-/
#check_msgs in
-- ANCHOR: plusNatFiveThreeAgain
#eval plus 5 3
-- ANCHOR_END: plusNatFiveThreeAgain
#check plus
-- ANCHOR: plusType
example : {α : Type} → [Plus α] → α → α → α := @Plus.plus
-- ANCHOR_END: plusType
/--
error: failed to synthesize
Plus Float
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: plusFloatFail
#eval plus 5.2 917.25861
-- ANCHOR_END: plusFloatFail
-- ANCHOR: PlusFloat
example := Plus Float
-- ANCHOR_END: PlusFloat
-- ANCHOR: Nat.zero
section
open Nat
example := zero
end
-- ANCHOR_END: Nat.zero
-- ANCHOR: Pos
inductive Pos : Type where
| one : Pos
| succ : Pos → Pos
-- ANCHOR_END: Pos
-- ANCHOR: PosStuff
example := Option Pos
example := Zero Pos
example := Nat.zero
-- ANCHOR_END: PosStuff
discarding
/--
error: failed to synthesize
OfNat Pos 7
numerals are polymorphic in Lean, but the numeral `7` cannot be used in a context where the expected type is
Pos
due to the absence of the instance above
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: sevenOops
def seven : Pos := 7
-- ANCHOR_END: sevenOops
stop discarding
-- ANCHOR: seven
def seven : Pos :=
Pos.succ (Pos.succ (Pos.succ (Pos.succ (Pos.succ (Pos.succ Pos.one)))))
-- ANCHOR_END: seven
discarding
/--
error: failed to synthesize
HAdd Pos Pos ?m.3
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: fourteenOops
def fourteen : Pos := seven + seven
-- ANCHOR_END: fourteenOops
stop discarding
/--
error: failed to synthesize
HMul Pos Pos ?m.3
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: fortyNineOops
def fortyNine : Pos := seven * seven
-- ANCHOR_END: fortyNineOops
-- ANCHOR: PlusPos
def Pos.plus : Pos → Pos → Pos
| Pos.one, k => Pos.succ k
| Pos.succ n, k => Pos.succ (n.plus k)
instance : Plus Pos where
plus := Pos.plus
def fourteen : Pos := plus seven seven
-- ANCHOR_END: PlusPos
-- ANCHOR: AddPos
instance : Add Pos where
add := Pos.plus
-- ANCHOR_END: AddPos
namespace Extra
-- ANCHOR: betterFourteen
def fourteen : Pos := seven + seven
-- ANCHOR_END: betterFourteen
end Extra
namespace Foo
variable {α β : Type} (x : α) (y : β) [HAdd α β γ]
-- ANCHOR: plusDesugar
example : x + y = HAdd.hAdd x y := rfl
-- ANCHOR_END: plusDesugar
end Foo
-- ANCHOR: readFile
example : System.FilePath → IO String := IO.FS.readFile
-- ANCHOR_END: readFile
-- ANCHOR: fileDumper
def fileDumper : IO Unit := do
let stdin ← IO.getStdin
let stdout ← IO.getStdout
stdout.putStr "Which file? "
stdout.flush
let f := (← stdin.getLine).trim
stdout.putStrLn s!"'The file {f}' contains:"
stdout.putStrLn (← IO.FS.readFile f)
-- ANCHOR_END: fileDumper
-- ANCHOR: posToNat
def Pos.toNat : Pos → Nat
| Pos.one => 1
| Pos.succ n => n.toNat + 1
-- ANCHOR_END: posToNat
namespace Argh
-- ANCHOR: posToStringStructure
def posToString (atTop : Bool) (p : Pos) : String :=
let paren s := if atTop then s else "(" ++ s ++ ")"
match p with
| Pos.one => "Pos.one"
| Pos.succ n => paren s!"Pos.succ {posToString false n}"
-- ANCHOR_END: posToStringStructure
-- ANCHOR: UglyToStringPos
instance : ToString Pos where
toString := posToString true
-- ANCHOR_END: UglyToStringPos
/-- info:
"There are Pos.succ (Pos.succ (Pos.succ (Pos.succ (Pos.succ (Pos.succ Pos.one)))))"
-/
#check_msgs in
-- ANCHOR: sevenLong
#eval s!"There are {seven}"
-- ANCHOR_END: sevenLong
end Argh
section Blah
-- ANCHOR: PosToStringNat
instance : ToString Pos where
toString x := toString (x.toNat)
-- ANCHOR_END: PosToStringNat
/-- info:
"There are 7"
-/
#check_msgs in
-- ANCHOR: sevenShort
#eval s!"There are {seven}"
-- ANCHOR_END: sevenShort
end Blah
/-- info:
7
-/
#check_msgs in
-- ANCHOR: sevenEvalStr
#eval seven
-- ANCHOR_END: sevenEvalStr
namespace Foo
variable {α β : Type} (x : α) (y : β) [HMul α β γ]
-- ANCHOR: timesDesugar
example : x * y = HMul.hMul x y := by rfl
-- ANCHOR_END: timesDesugar
end Foo
-- ANCHOR: PosMul
def Pos.mul : Pos → Pos → Pos
| Pos.one, k => k
| Pos.succ n, k => n.mul k + k
instance : Mul Pos where
mul := Pos.mul
-- ANCHOR_END: PosMul
/-- info:
[7, 49, 14]
-/
#check_msgs in
-- ANCHOR: muls
#eval [seven * Pos.one,
seven * seven,
Pos.succ Pos.one * seven]
-- ANCHOR_END: muls
namespace NatLits
-- ANCHOR: Zero
class Zero (α : Type) where
zero : α
-- ANCHOR_END: Zero
-- ANCHOR: One
class One (α : Type) where
one : α
-- ANCHOR_END: One
-- ANCHOR: OneExamples
example {α : Type} := [One α, OfNat α 1]
-- ANCHOR_END: OneExamples
-- Test that One works with OfNat _ 1
example [_root_.One α] : α := 1
-- Test the other ways around
example [_root_.OfNat α 1] : _root_.One α := inferInstance
example [_root_.OfNat α 0] : _root_.Zero α := inferInstance
-- ANCHOR: OfNat
class OfNat (α : Type) (_ : Nat) where
ofNat : α
-- ANCHOR_END: OfNat
end NatLits
similar datatypes Zero NatLits.Zero
similar datatypes One NatLits.One
similar datatypes OfNat NatLits.OfNat
-- ANCHOR: LT4
inductive LT4 where
| zero
| one
| two
| three
-- ANCHOR_END: LT4
-- ANCHOR: LT4ofNat
instance : OfNat LT4 0 where
ofNat := LT4.zero
instance : OfNat LT4 1 where
ofNat := LT4.one
instance : OfNat LT4 2 where
ofNat := LT4.two
instance : OfNat LT4 3 where
ofNat := LT4.three
-- ANCHOR_END: LT4ofNat
/-- info:
LT4.three
-/
#check_msgs in
-- ANCHOR: LT4three
#eval (3 : LT4)
-- ANCHOR_END: LT4three
/-- info:
LT4.zero
-/
#check_msgs in
-- ANCHOR: LT4zero
#eval (0 : LT4)
-- ANCHOR_END: LT4zero
/--
error: failed to synthesize
OfNat LT4 4
numerals are polymorphic in Lean, but the numeral `4` cannot be used in a context where the expected type is
LT4
due to the absence of the instance above
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: LT4four
#eval (4 : LT4)
-- ANCHOR_END: LT4four
-- ANCHOR: OnePos
instance : One Pos where
one := Pos.one
-- ANCHOR_END: OnePos
/-- info: 1 -/
#check_msgs in
-- ANCHOR: onePos
#eval (1 : Pos)
-- ANCHOR_END: onePos
-- ANCHOR: OfNatPos
instance : OfNat Pos (n + 1) where
ofNat :=
let rec natPlusOne : Nat → Pos
| 0 => Pos.one
| k + 1 => Pos.succ (natPlusOne k)
natPlusOne n
-- ANCHOR_END: OfNatPos
-- ANCHOR: eight
def eight : Pos := 8
-- ANCHOR_END: eight
/--
error: failed to synthesize
OfNat Pos 0
numerals are polymorphic in Lean, but the numeral `0` cannot be used in a context where the expected type is
Pos
due to the absence of the instance above
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: zeroBad
def zero : Pos := 0
-- ANCHOR_END: zeroBad
namespace AltPos
-- ANCHOR: AltPos
structure Pos where
succ ::
pred : Nat
-- ANCHOR_END: AltPos
end AltPos
-- ANCHOR: printlnType
example : {α : Type} → [ToString α] → α → IO Unit := @IO.println
-- ANCHOR_END: printlnType
/-- info:
IO.println : ?m.2620 → IO Unit
-/
#check_msgs in
-- ANCHOR: printlnMetas
#check (IO.println)
-- ANCHOR_END: printlnMetas
/-- info: @IO.println : {α : Type u_1} → [ToString α] → α → IO Unit -/
#check_msgs in
-- ANCHOR: printlnNoMetas
#check @IO.println
-- ANCHOR_END: printlnNoMetas
discarding
-- ANCHOR: ListSum
def List.sumOfContents [Add α] [OfNat α 0] : List α → α
| [] => 0
| x :: xs => x + xs.sumOfContents
-- ANCHOR_END: ListSum
stop discarding
-- ANCHOR: ListSumZ
def List.sumOfContents [Add α] [Zero α] : List α → α
| [] => 0
| x :: xs => x + xs.sumOfContents
-- ANCHOR_END: ListSumZ
-- ANCHOR: fourNats
def fourNats : List Nat := [1, 2, 3, 4]
-- ANCHOR_END: fourNats
-- ANCHOR: fourPos
def fourPos : List Pos := [1, 2, 3, 4]
-- ANCHOR_END: fourPos
/-- info:
10
-/
#check_msgs in
-- ANCHOR: fourNatsSum
#eval fourNats.sumOfContents
-- ANCHOR_END: fourNatsSum
/--
error: failed to synthesize
Zero Pos
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: fourPosSum
#eval fourPos.sumOfContents
-- ANCHOR_END: fourPosSum
namespace PointStuff
-- ANCHOR: PPoint
structure PPoint (α : Type) where
x : α
y : α
-- ANCHOR_END: PPoint
-- ANCHOR: AddPPoint
instance [Add α] : Add (PPoint α) where
add p1 p2 := { x := p1.x + p2.x, y := p1.y + p2.y }
-- ANCHOR_END: AddPPoint
-- ANCHOR: AddPPointNat
example := Add (PPoint Nat)
example := Add Nat
-- ANCHOR_END: AddPPointNat
-- ANCHOR: MulPPoint
instance [Mul α] : HMul (PPoint α) α (PPoint α) where
hMul p z := {x := p.x * z, y := p.y * z}
-- ANCHOR_END: MulPPoint
/-- info:
{ x := 5.000000, y := 7.400000 }
-/
#check_msgs in
-- ANCHOR: HMulPPoint
#eval {x := 2.5, y := 3.7 : PPoint Float} * 2.0
-- ANCHOR_END: HMulPPoint
end PointStuff
-- ANCHOR: ofNatType
example : {α : Type} → (n : Nat) → [OfNat α n] → α := @OfNat.ofNat
-- ANCHOR_END: ofNatType
-- ANCHOR: addType
example : {α : Type} → [Add α] → α → α → α := @Add.add
-- ANCHOR_END: addType
namespace Foo
section
variable {α β : Type} (x : α) (y : β)
variable [HSub α β γ] [HDiv α β γ] [HMod α β γ] [HPow α β γ]
-- ANCHOR: minusDesugar
example : x - y = HSub.hSub x y := rfl
-- ANCHOR_END: minusDesugar
end
section
variable {α β : Type} (x : α) (y : β)
variable [HSub α β γ] [HDiv α β γ] [HMod α β γ] [HPow α β γ]
-- ANCHOR: divDesugar
example : x / y = HDiv.hDiv x y := rfl
-- ANCHOR_END: divDesugar
end
section
variable {α β : Type} (x : α) (y : β)
variable [HSub α β γ] [HDiv α β γ] [HMod α β γ] [HPow α β γ]
-- ANCHOR: modDesugar
example : x % y = HMod.hMod x y := rfl
-- ANCHOR_END: modDesugar
end
section
variable {α β : Type} (x : α) (y : β)
variable [HSub α β γ] [HDiv α β γ] [HMod α β γ] [HPow α β γ]
-- ANCHOR: powDesugar
example : x ^ y = HPow.hPow x y := rfl
-- ANCHOR_END: powDesugar
end
section
variable {α β : Type} (x : α) (y : β)
variable [HSub α β γ] [HDiv α β γ] [HMod α β γ] [HPow α β γ]
variable (y : α) [LT α] [LE α]
-- ANCHOR: ltDesugar
example : (x < y) = LT.lt x y := rfl
-- ANCHOR_END: ltDesugar
end
section
variable {α β : Type} (x : α) (y : β)
variable [HSub α β γ] [HDiv α β γ] [HMod α β γ] [HPow α β γ]
variable (y : α) [LT α] [LE α]
-- ANCHOR: leDesugar
example : (x ≤ y) = LE.le x y := rfl
-- ANCHOR_END: leDesugar
end
section
variable {α β : Type} (x : α) (y : β)
variable [HSub α β γ] [HDiv α β γ] [HMod α β γ] [HPow α β γ]
variable (y : α) [LT α] [LE α]
-- ANCHOR: gtDesugar
example : (x > y) = LT.lt y x := by rfl
-- ANCHOR_END: gtDesugar
end
section
variable {α β : Type} (x : α) (y : β)
variable [HSub α β γ] [HDiv α β γ] [HMod α β γ] [HPow α β γ]
variable (y : α) [LT α] [LE α]
-- ANCHOR: geDesugar
example : (x ≥ y) = LE.le y x := by rfl
-- ANCHOR_END: geDesugar
end
section
variable {α β : Type} (x : α) (y : β)
variable [HSub α β γ] [HDiv α β γ] [HMod α β γ] [HPow α β γ]
variable (y : α) [LT α] [LE α]
--ANCHOR: ordSugarClasses
example := [LE, LT]
--ANCHOR_END: ordSugarClasses
end
end Foo
namespace OverloadedInt
variable {α : Type} (x : α) [Neg α]
-- ANCHOR: negDesugar
example : (- x) = Neg.neg x := rfl
-- ANCHOR_END: negDesugar
end OverloadedInt
namespace OverloadedBits
-- ANCHOR: UInt8
example : Type := UInt8
-- ANCHOR_END: UInt8
-- ANCHOR: UInt16
example : Type := UInt16
-- ANCHOR_END: UInt16
-- ANCHOR: UInt32
example : Type := UInt32
-- ANCHOR_END: UInt32
-- ANCHOR: UInt64
example : Type := UInt64
-- ANCHOR_END: UInt64
-- ANCHOR: USize
example : Type := USize
-- ANCHOR_END: USize
section
variable {x: α} {y : β} [HAnd α β γ]
-- ANCHOR: bAndDesugar
example : x &&& y = HAnd.hAnd x y := rfl
-- ANCHOR_END: bAndDesugar
end
section
variable {x: α} {y : β} [HOr α β γ]
-- ANCHOR: bOrDesugar
example : x ||| y = HOr.hOr x y := rfl
-- ANCHOR_END: bOrDesugar
end
section
variable {x: α} {y : β} [HXor α β γ]
-- ANCHOR: bXorDesugar
example : x ^^^ y = HXor.hXor x y := rfl
-- ANCHOR_END: bXorDesugar
end
section
variable {x: α} [Complement α]
-- ANCHOR: complementDesugar
example : ~~~ x = Complement.complement x := rfl
-- ANCHOR_END: complementDesugar
end
section
variable {x: α} {y : β} [HShiftRight α β γ]
-- ANCHOR: shrDesugar
example : x >>> y = HShiftRight.hShiftRight x y := rfl
-- ANCHOR_END: shrDesugar
end
section
variable {x: α} {y : β} [HShiftLeft α β γ]
-- ANCHOR: shlDesugar
example : x <<< y = HShiftLeft.hShiftLeft x y := rfl
-- ANCHOR_END: shlDesugar
end
section
variable {x y : α} [BEq α]
-- ANCHOR: beqDesugar
example : (x == y) = BEq.beq x y := rfl
-- ANCHOR_END: beqDesugar
end
end OverloadedBits
-- ANCHOR: addNatPos
def addNatPos : Nat → Pos → Pos
| 0, p => p
| n + 1, p => Pos.succ (addNatPos n p)
def addPosNat : Pos → Nat → Pos
| p, 0 => p
| p, n + 1 => Pos.succ (addPosNat p n)
-- ANCHOR_END: addNatPos
-- ANCHOR: haddInsts
instance : HAdd Nat Pos Pos where
hAdd := addNatPos
instance : HAdd Pos Nat Pos where
hAdd := addPosNat
-- ANCHOR_END: haddInsts
/-- info:
8
-/
#check_msgs in
-- ANCHOR: posNatEx
#eval (3 : Pos) + (5 : Nat)
-- ANCHOR_END: posNatEx
/-- info:
8
-/
#check_msgs in
-- ANCHOR: natPosEx
#eval (3 : Nat) + (5 : Pos)
-- ANCHOR_END: natPosEx
namespace ProblematicHPlus
-- ANCHOR: HPlus
class HPlus (α : Type) (β : Type) (γ : Type) where
hPlus : α → β → γ
-- ANCHOR_END: HPlus
-- ANCHOR: HPlusInstances
instance : HPlus Nat Pos Pos where
hPlus := addNatPos
instance : HPlus Pos Nat Pos where
hPlus := addPosNat
-- ANCHOR_END: HPlusInstances
/--
error: typeclass instance problem is stuck
HPlus Pos Nat ?m.6
Note: Lean will not try to resolve this typeclass instance problem because the third type argument to `HPlus` is a metavariable. This argument must be fully determined before Lean will try to resolve the typeclass.
Hint: Adding type annotations and supplying implicit arguments to functions can give Lean more information for typeclass resolution. For example, if you have a variable `x` that you intend to be a `Nat`, but Lean reports it as having an unresolved type like `?m`, replacing `x` with `(x : Nat)` can get typeclass resolution un-stuck.
-/
#check_msgs in
-- ANCHOR: hPlusOops
#eval toString (HPlus.hPlus (3 : Pos) (5 : Nat))
-- ANCHOR_END: hPlusOops
/-- info:
8
-/
#check_msgs in
-- ANCHOR: hPlusLotsaTypes
#eval (HPlus.hPlus (3 : Pos) (5 : Nat) : Pos)
-- ANCHOR_END: hPlusLotsaTypes
end ProblematicHPlus
inductive Even where
| zero
| plusTwo : Even → Even
instance : OfNat Even 0 where
ofNat := .zero
instance [OfNat Even n] : OfNat Even (n + 2) where
ofNat := .plusTwo (OfNat.ofNat n)
#eval (6 : Even)
namespace BetterHPlus
-- ANCHOR: HPlusOut
class HPlus (α : Type) (β : Type) (γ : outParam Type) where
hPlus : α → β → γ
-- ANCHOR_END: HPlusOut
instance : HPlus Nat Pos Pos where
hPlus := addNatPos
instance : HPlus Pos Nat Pos where
hPlus := addPosNat
/-- info:
8
-/
#check_msgs in
-- ANCHOR: hPlusWorks
#eval HPlus.hPlus (3 : Pos) (5 : Nat)
-- ANCHOR_END: hPlusWorks
-- ANCHOR: notDefaultAdd
instance [Add α] : HPlus α α α where
hPlus := Add.add
-- ANCHOR_END: notDefaultAdd
/-- info:
8
-/
#check_msgs in
-- ANCHOR: hPlusNatNat
#eval HPlus.hPlus (3 : Nat) (5 : Nat)
-- ANCHOR_END: hPlusNatNat
/-- info:
HPlus.hPlus 5 3 : Nat
-/
#check_msgs in
-- ANCHOR: plusFiveThree
#check HPlus.hPlus (5 : Nat) (3 : Nat)
-- ANCHOR_END: plusFiveThree
/-- info:
HPlus.hPlus 5 : ?m.6076 → ?m.6078
-/
#check_msgs in
-- ANCHOR: plusFiveMeta
#check HPlus.hPlus (5 : Nat)
-- ANCHOR_END: plusFiveMeta
-- ANCHOR: defaultAdd
@[default_instance]
instance [Add α] : HPlus α α α where
hPlus := Add.add
-- ANCHOR_END: defaultAdd
/-- info:
HPlus.hPlus 5 : Nat → Nat
-/
#check_msgs in
-- ANCHOR: plusFive
#check HPlus.hPlus (5 : Nat)
-- ANCHOR_END: plusFive
end BetterHPlus
similar datatypes ProblematicHPlus.HPlus BetterHPlus.HPlus
-- ANCHOR: fiveType
example : Nat := 5
-- ANCHOR_END: fiveType
-- ANCHOR: northernTrees
def northernTrees : Array String :=
#["sloe", "birch", "elm", "oak"]
-- ANCHOR_END: northernTrees
-- ANCHOR: northernTreesSize
example : northernTrees.size = 4 := rfl
-- ANCHOR_END: northernTreesSize
-- ANCHOR: northernTreesTwo
example : northernTrees[2] = "elm" := rfl
-- ANCHOR_END: northernTreesTwo
/-- error:
failed to prove index is valid, possible solutions:
- Use `have`-expressions to prove the index is valid
- Use `a[i]!` notation instead, runtime check is performed, and 'Panic' error message is produced if index is not valid
- Use `a[i]?` notation instead, result is an `Option` type
- Use `a[i]'h` notation instead, where `h` is a proof that index is valid
⊢ 8 < northernTrees.size
-/
#check_msgs in
-- ANCHOR: northernTreesEight
-- TODO ensure correct quote in book
example := northernTrees[8]
-- ANCHOR_END: northernTreesEight
inductive EvenList (α : Type) : Type where
| nil : EvenList α
| cons : α → α → EvenList α → EvenList α
-- ANCHOR: NonEmptyList
structure NonEmptyList (α : Type) : Type where
head : α
tail : List α
-- ANCHOR_END: NonEmptyList
def NonEmptyList.toList (xs : NonEmptyList α) := xs.head :: xs.tail
-- ANCHOR: coeNope
example {α : _} := Coe (List α) (NonEmptyList α)
-- ANCHOR_END: coeNope
-- ANCHOR: idahoSpiders
def idahoSpiders : NonEmptyList String := {
head := "Banded Garden Spider",
tail := [
"Long-legged Sac Spider",
"Wolf Spider",
"Hobo Spider",
"Cat-faced Spider"
]
}
-- ANCHOR_END: idahoSpiders
-- ANCHOR: firstSpider
example : -- TODO there was a name overlap - check it
idahoSpiders.head = "Banded Garden Spider" := rfl
-- ANCHOR_END: firstSpider
-- ANCHOR: moreSpiders
example : idahoSpiders.tail.length = 4 := rfl
-- ANCHOR_END: moreSpiders
-- ANCHOR: NEListGetHuh
def NonEmptyList.get? : NonEmptyList α → Nat → Option α
| xs, 0 => some xs.head
| {head := _, tail := []}, _ + 1 => none
| {head := _, tail := h :: t}, n + 1 => get? {head := h, tail := t} n
-- ANCHOR_END: NEListGetHuh
namespace UseList
-- ANCHOR: NEListGetHuhList
def NonEmptyList.get? : NonEmptyList α → Nat → Option α
| xs, 0 => some xs.head
| xs, n + 1 => xs.tail[n]?
-- ANCHOR_END: NEListGetHuhList
end UseList
-- ANCHOR: inBoundsNEList
abbrev NonEmptyList.inBounds (xs : NonEmptyList α) (i : Nat) : Prop :=
i ≤ xs.tail.length
-- ANCHOR_END: inBoundsNEList
-- ANCHOR: NEListGet
def NonEmptyList.get (xs : NonEmptyList α)
(i : Nat) (ok : xs.inBounds i) : α :=
match i with
| 0 => xs.head
| n + 1 => xs.tail[n]
-- ANCHOR_END: NEListGet
-- ANCHOR: spiderBoundsChecks
theorem atLeastThreeSpiders : idahoSpiders.inBounds 2 := by decide
theorem notSixSpiders : ¬idahoSpiders.inBounds 5 := by decide
-- ANCHOR_END: spiderBoundsChecks
namespace Foo
-- ANCHOR: spiderBoundsChecks'
theorem atLeastThreeSpiders : idahoSpiders.inBounds 2 := by decide
theorem notSixSpiders : ¬(idahoSpiders.inBounds 5) := by decide
-- ANCHOR_END: spiderBoundsChecks'
end Foo
namespace Demo
-- ANCHOR: GetElem
class GetElem
(coll : Type)
(idx : Type)
(item : outParam Type)
(inBounds : outParam (coll → idx → Prop)) where
getElem : (c : coll) → (i : idx) → inBounds c i → item
-- ANCHOR_END: GetElem
end Demo
similar datatypes GetElem Demo.GetElem
-- ANCHOR: GetElemNEList
instance : GetElem (NonEmptyList α) Nat α NonEmptyList.inBounds where
getElem := NonEmptyList.get
-- ANCHOR_END: GetElemNEList
-- ANCHOR: firstSpiderZero
example : idahoSpiders[0] = "Banded Garden Spider" := rfl
-- ANCHOR_END: firstSpiderZero
/-- error:
failed to prove index is valid, possible solutions:
- Use `have`-expressions to prove the index is valid
- Use `a[i]!` notation instead, runtime check is performed, and 'Panic' error message is produced if index is not valid
- Use `a[i]?` notation instead, result is an `Option` type
- Use `a[i]'h` notation instead, where `h` is a proof that index is valid
⊢ idahoSpiders.inBounds 9
-/
#check_msgs in
-- ANCHOR: tenthSpider
-- TODO ensure correct quote
example := idahoSpiders[9]
-- ANCHOR_END: tenthSpider
-- ANCHOR: ListPosElem
instance : GetElem (List α) Pos α
(fun list n => list.length > n.toNat) where
getElem (xs : List α) (i : Pos) ok := xs[i.toNat]
-- ANCHOR_END: ListPosElem
namespace PointStuff
-- ANCHOR: PPointBoolGetElem
instance : GetElem (PPoint α) Bool α (fun _ _ => True) where
getElem (p : PPoint α) (i : Bool) _ :=
if not i then p.x else p.y
-- ANCHOR_END: PPointBoolGetElem
instance : GetElem (PPoint α) Nat α (fun _ n => n < 2) where
getElem (p : PPoint α) (i : Nat) _ :=
match i with
| 0 => p.x
| 1 => p.y
end PointStuff
-- ANCHOR: boolEqTrue
example : ("Octopus" == "Cuttlefish") = false := rfl
-- ANCHOR_END: boolEqTrue
-- ANCHOR: boolEqFalse
example : ("Octopodes" == "Octo".append "podes") = true := rfl
-- ANCHOR_END: boolEqFalse
/--
error: failed to synthesize
BEq (Nat → Nat)
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: functionEq
-- TODO quote check
example := (fun (x : Nat) => 1 + x) == (Nat.succ ·)
-- ANCHOR_END: functionEq
-- ANCHOR: functionEqProp
example : Prop := (fun (x : Nat) => 1 + x) = (Nat.succ ·)
-- ANCHOR_END: functionEqProp
-- ANCHOR: LTPos
instance : LT Pos where
lt x y := LT.lt x.toNat y.toNat
-- ANCHOR_END: LTPos
-- ANCHOR: LEPos
instance : LE Pos where
le x y := LE.le x.toNat y.toNat
-- ANCHOR_END: LEPos
-- ANCHOR: DecLTLEPos
instance {x : Pos} {y : Pos} : Decidable (x < y) :=
inferInstanceAs (Decidable (x.toNat < y.toNat))
instance {x : Pos} {y : Pos} : Decidable (x ≤ y) :=
inferInstanceAs (Decidable (x.toNat ≤ y.toNat))
-- ANCHOR_END: DecLTLEPos
/--
error: Type mismatch
inferInstanceAs (Decidable (x.toNat < y.toNat))
has type
Decidable (x.toNat < y.toNat)
but is expected to have type
Decidable (x ≤ y)
-/
#check_msgs in
-- ANCHOR: LTLEMismatch
instance {x : Pos} {y : Pos} : Decidable (x ≤ y) :=
inferInstanceAs (Decidable (x.toNat < y.toNat))
-- ANCHOR_END: LTLEMismatch
#eval (5 : Pos) < (3 : Pos)
example : (fun (x : Nat) => 1 + x) = (Nat.succ ·) := by ext; simp +arith
-- Example for exercise
inductive Method where
| GET
| POST
| PUT
| DELETE
structure Response where
class HTTP (m : Method) where
doTheWork : (uri : String) → IO Response
/-- info:
2 < 4 : Prop
-/
#check_msgs in
-- ANCHOR: twoLessFour
#check 2 < 4
-- ANCHOR_END: twoLessFour
/--
error: failed to synthesize
Decidable ((fun x => 1 + x) = fun x => x.succ)
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: funEqDec
-- TODO quote check
example := if (fun (x : Nat) => 1 + x) = (Nat.succ ·) then "yes" else "no"
-- ANCHOR_END: funEqDec
--- ANCHOR: ifProp
example : (
if 2 < 4 then 1 else 2
) = (
1
) := rfl
--- ANCHOR_END: ifProp
namespace Cmp
-- ANCHOR: Ordering
inductive Ordering where
| lt
| eq
| gt
-- ANCHOR_END: Ordering
end Cmp
similar datatypes Ordering Cmp.Ordering
-- ANCHOR: OrdPos
def Pos.comp : Pos → Pos → Ordering
| Pos.one, Pos.one => Ordering.eq
| Pos.one, Pos.succ _ => Ordering.lt
| Pos.succ _, Pos.one => Ordering.gt
| Pos.succ n, Pos.succ k => comp n k
instance : Ord Pos where
compare := Pos.comp
-- ANCHOR_END: OrdPos
namespace H
-- ANCHOR: Hashable
class Hashable (α : Type) where
hash : α → UInt64
-- ANCHOR_END: Hashable
end H
-- ANCHOR: HashableSpec
section
variable {α : Type} (x y : α) [BEq α] [Hashable α]
example := x == y
example := hash x == hash y
example := x ≠ y
end
-- ANCHOR_END: HashableSpec
similar datatypes Hashable H.Hashable
-- ANCHOR: mixHash
example : UInt64 → UInt64 → UInt64 := mixHash
-- ANCHOR_END: mixHash
-- ANCHOR: HashablePos
def hashPos : Pos → UInt64
| Pos.one => 0
| Pos.succ n => mixHash 1 (hashPos n)
instance : Hashable Pos where
hash := hashPos
-- ANCHOR_END: HashablePos
-- ANCHOR: TreeHash
inductive BinTree (α : Type) where
| leaf : BinTree α
| branch : BinTree α → α → BinTree α → BinTree α
def eqBinTree [BEq α] : BinTree α → BinTree α → Bool
| BinTree.leaf, BinTree.leaf =>
true
| BinTree.branch l x r, BinTree.branch l2 x2 r2 =>
x == x2 && eqBinTree l l2 && eqBinTree r r2
| _, _ =>
false
instance [BEq α] : BEq (BinTree α) where
beq := eqBinTree
def hashBinTree [Hashable α] : BinTree α → UInt64
| BinTree.leaf =>
0
| BinTree.branch left x right =>
mixHash 1
(mixHash (hashBinTree left)
(mixHash (hash x)
(hashBinTree right)))
instance [Hashable α] : Hashable (BinTree α) where
hash := hashBinTree
-- ANCHOR_END: TreeHash
-- ANCHOR: HashableNonEmptyList
instance [Hashable α] : Hashable (NonEmptyList α) where
hash xs := mixHash (hash xs.head) (hash xs.tail)
-- ANCHOR_END: HashableNonEmptyList
-- ANCHOR: BEqHashableDerive
deriving instance BEq, Hashable for Pos
deriving instance BEq, Hashable for NonEmptyList
-- ANCHOR_END: BEqHashableDerive
/-- error: No deriving handlers have been implemented for class `ToString` -/
#check_msgs in
-- ANCHOR: derivingNotFound
deriving instance ToString for NonEmptyList
-- ANCHOR_END: derivingNotFound
namespace A
-- ANCHOR: HAppend
class HAppend (α : Type) (β : Type) (γ : outParam Type) where
hAppend : α → β → γ
-- ANCHOR_END: HAppend
end A
similar datatypes HAppend A.HAppend
namespace AppendOverloads
section
variable {α β γ : Type} (xs : α) (ys : β) [HAppend α β γ]
-- ANCHOR: desugarHAppend
example : xs ++ ys = HAppend.hAppend xs ys := rfl
-- ANCHOR_END: desugarHAppend
end
end AppendOverloads
-- ANCHOR: AppendNEList
instance : Append (NonEmptyList α) where
append xs ys :=
{ head := xs.head, tail := xs.tail ++ ys.head :: ys.tail }
-- ANCHOR_END: AppendNEList
/-- info:
{ head := "Banded Garden Spider",
tail := ["Long-legged Sac Spider",
"Wolf Spider",
"Hobo Spider",
"Cat-faced Spider",
"Banded Garden Spider",
"Long-legged Sac Spider",
"Wolf Spider",
"Hobo Spider",
"Cat-faced Spider"] }
-/
#check_msgs in
-- ANCHOR: appendSpiders
#eval idahoSpiders ++ idahoSpiders
-- ANCHOR_END: appendSpiders
-- ANCHOR: AppendNEListList
instance : HAppend (NonEmptyList α) (List α) (NonEmptyList α) where
hAppend xs ys :=
{ head := xs.head, tail := xs.tail ++ ys }
-- ANCHOR_END: AppendNEListList
/-- info:
{ head := "Banded Garden Spider",
tail := ["Long-legged Sac Spider", "Wolf Spider", "Hobo Spider", "Cat-faced Spider", "Trapdoor Spider"] }
-/
#check_msgs in
-- ANCHOR: appendSpidersList
#eval idahoSpiders ++ ["Trapdoor Spider"]
-- ANCHOR_END: appendSpidersList
section
-- ANCHOR: optionFMeta
variable {α β : Type} (f : α → β)
example := Option
example : Functor.map f none = none := rfl
example : Functor.map f (some x) = some (f x) := rfl
-- ANCHOR_END: optionFMeta
end
section
-- ANCHOR: FunctorLaws
variable {α β γ : Type} (g : α → β) (f : β → γ) {F : Type → Type} [Functor F] (x : F α)
example := id <$> x
open Functor
example := map (fun y => f (g y)) x
example := map f (map g x)
-- ANCHOR_END: FunctorLaws
end
-- ANCHOR: mapList
example : Functor.map (· + 5) [1, 2, 3] = [6, 7, 8] := rfl
-- ANCHOR_END: mapList
-- ANCHOR: mapOption
example : Functor.map toString (some (List.cons 5 List.nil)) = some "[5]" := by decide +native -- TODO verify text and perhaps replace
-- ANCHOR_END: mapOption
-- ANCHOR: mapListList
example : Functor.map List.reverse [[1, 2, 3], [4, 5, 6]] = [[3, 2, 1], [6, 5, 4]] := rfl
-- ANCHOR_END: mapListList
-- ANCHOR: mapInfixList
example : (· + 5) <$> [1, 2, 3] = [6, 7, 8] := rfl
-- ANCHOR_END: mapInfixList
-- ANCHOR: mapInfixOption
example : toString <$> (some (List.cons 5 List.nil)) = some "[5]" := by decide +native
-- ANCHOR_END: mapInfixOption
-- ANCHOR: mapInfixListList
example : List.reverse <$> [[1, 2, 3], [4, 5, 6]] = [[3, 2, 1], [6, 5, 4]] := rfl
-- ANCHOR_END: mapInfixListList
-- ANCHOR: FunctorNonEmptyList
instance : Functor NonEmptyList where
map f xs := { head := f xs.head, tail := f <$> xs.tail }
-- ANCHOR_END: FunctorNonEmptyList
section
variable {α : Type}
-- ANCHOR: FunctorNonEmptyListA
example := NonEmptyList α
example := NonEmptyList Nat
-- ANCHOR_END: FunctorNonEmptyListA
end
namespace PointStuff
-- ANCHOR: FunctorPPointBad
instance : Functor PPoint where
map f p := let x := p.x; have := f x; { x := f p.x, y := f p.x }
-- ANCHOR_END: FunctorPPointBad
-- ANCHOR: FunctorPPoint
instance : Functor PPoint where
map f p := { x := f p.x, y := f p.y }
-- ANCHOR_END: FunctorPPoint
-- ANCHOR: NEPP
example := NonEmptyList (PPoint Nat)
-- ANCHOR_END: NEPP
end PointStuff
-- ANCHOR: concat
def concat [Append α] (xs : NonEmptyList α) : α :=
let rec catList (start : α) : List α → α
| [] => start
| (z :: zs) => catList (start ++ z) zs
catList xs.head xs.tail
-- ANCHOR_END: concat
-- Just a quick test, not used in the book
-- ANCHOR: concatText
example : concat idahoSpiders = "Banded Garden SpiderLong-legged Sac SpiderWolf SpiderHobo SpiderCat-faced Spider" := rfl
-- ANCHOR_END: concatText
namespace FakeFunctor
-- ANCHOR: FunctorDef
class Functor (f : Type → Type) where
map : {α β : Type} → (α → β) → f α → f β
mapConst {α β : Type} (x : α) (coll : f β) : f α :=
map (fun _ => x) coll
-- ANCHOR_END: FunctorDef
end FakeFunctor
similar datatypes FakeFunctor.Functor Functor
namespace Whatevs
axiom α : Type
axiom β : Type
axiom γ : Type
axiom f : β → γ
axiom g : α → β
-- ANCHOR: compDef
example : f ∘ g = fun y => f (g y) := rfl
-- ANCHOR_END: compDef
end Whatevs
-- Coercions
-- ANCHOR: drop
example : {α : Type} → Nat → List α → List α := @List.drop
-- ANCHOR_END: drop
/--
error: Application type mismatch: The argument
2
has type
Pos
but is expected to have type
Nat
in the application
List.drop 2
-/
#check_msgs in
-- ANCHOR: dropPos
-- TODO quote check
example := [1, 2, 3, 4].drop (2 : Pos)
-- ANCHOR_END: dropPos
namespace FakeCoe
-- ANCHOR: Coe
class Coe (α : Type) (β : Type) where
coe : α → β
-- ANCHOR_END: Coe
-- ANCHOR: CoeTail
class CoeTail (α : Type) (β : Type) where
coe : α → β
-- ANCHOR_END: CoeTail
-- ANCHOR: CoeHead
class CoeHead (α : Type) (β : Type) where
coe : α → β
-- ANCHOR_END: CoeHead
end FakeCoe
similar datatypes Coe FakeCoe.Coe
similar datatypes CoeTail FakeCoe.CoeTail
similar datatypes CoeHead FakeCoe.CoeHead
-- ANCHOR: CoeOption
instance : Coe α (Option α) where
coe x := some x
-- ANCHOR_END: CoeOption
namespace L
-- ANCHOR: lastHuh
def List.last? : List α → Option α
| [] => none
| [x] => x
| _ :: x :: xs => last? (x :: xs)
-- ANCHOR_END: lastHuh
end L
-- ANCHOR: perhapsPerhapsPerhaps
def perhapsPerhapsPerhaps : Option (Option (Option String)) :=
"Please don't tell me"
-- ANCHOR_END: perhapsPerhapsPerhaps
discarding
/--
error: failed to synthesize
OfNat (Option (Option (Option Nat))) 392
numerals are polymorphic in Lean, but the numeral `392` cannot be used in a context where the expected type is
Option (Option (Option Nat))
due to the absence of the instance above
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: ofNatBeforeCoe
def perhapsPerhapsPerhapsNat : Option (Option (Option Nat)) :=
392
-- ANCHOR_END: ofNatBeforeCoe
stop discarding
-- ANCHOR: perhapsPerhapsPerhapsNat
def perhapsPerhapsPerhapsNat : Option (Option (Option Nat)) :=
(392 : Nat)
-- ANCHOR_END: perhapsPerhapsPerhapsNat
namespace Up
-- ANCHOR: perhapsPerhapsPerhapsNatUp
def perhapsPerhapsPerhapsNat : Option (Option (Option Nat)) :=
↑(392 : Nat)
-- ANCHOR_END: perhapsPerhapsPerhapsNatUp
end Up
-- ANCHOR: CoeNEList
instance : Coe (NonEmptyList α) (List α) where
coe
| { head := x, tail := xs } => x :: xs
-- ANCHOR_END: CoeNEList
namespace Foo
-- ANCHOR: CoeDep
class CoeDep (α : Type) (x : α) (β : Type) where
coe : β
-- ANCHOR_END: CoeDep
end Foo
similar datatypes CoeDep Foo.CoeDep
-- ANCHOR: CoeDepListNEList
instance : CoeDep (List α) (x :: xs) (NonEmptyList α) where
coe := { head := x, tail := xs }
-- ANCHOR_END: CoeDepListNEList
/--
error: Type mismatch
[]
has type
List ?m.2
but is expected to have type
NonEmptyList Nat
-/
#check_msgs in
#eval ([] : NonEmptyList Nat)
/-- info: { head := 1, tail := [2, 3] } -/
#guard_msgs in
#eval ([1, 2, 3] : NonEmptyList Nat)
-- ANCHOR: JSON
inductive JSON where
| true : JSON
| false : JSON
| null : JSON
| string : String → JSON
| number : Float → JSON
| object : List (String × JSON) → JSON
| array : List JSON → JSON
-- ANCHOR_END: JSON
/-- info:
"5.000000"
-/
#check_msgs in
-- ANCHOR: fiveZeros
#eval (5 : Float).toString
-- ANCHOR_END: fiveZeros
-- ANCHOR: Stringseparate
def String.separate (sep : String) (strings : List String) : String :=
match strings with
| [] => ""
| x :: xs => String.join (x :: xs.map (sep ++ ·))
-- ANCHOR_END: Stringseparate
/-- info:
"1, 2"
-/
#check_msgs in
-- ANCHOR: sep2ex
#eval ", ".separate ["1", "2"]
-- ANCHOR_END: sep2ex
/-- info:
"1"
-/
#check_msgs in
-- ANCHOR: sep1ex
#eval ", ".separate ["1"]
-- ANCHOR_END: sep1ex
/-- info:
""
-/
#check_msgs in
-- ANCHOR: sep0ex
#eval ", ".separate []
-- ANCHOR_END: sep0ex
-- ANCHOR: dropDecimals
def dropDecimals (numString : String) : String :=
if numString.contains '.' then
let noTrailingZeros := numString.dropRightWhile (· == '0')
noTrailingZeros.dropRightWhile (· == '.')
else numString
-- ANCHOR_END: dropDecimals
/-- info:
"5"
-/
#check_msgs in
-- ANCHOR: dropDecimalExample
#eval dropDecimals (5 : Float).toString
-- ANCHOR_END: dropDecimalExample
/-- info:
"5.2"
-/
#check_msgs in
-- ANCHOR: dropDecimalExample2
#eval dropDecimals (5.2 : Float).toString
-- ANCHOR_END: dropDecimalExample2
/-- info:
"\\\"Hello!\\\""
-/
#check_msgs in
-- ANCHOR: escapeQuotes
#eval Lean.Json.escape "\"Hello!\""
-- ANCHOR_END: escapeQuotes
-- ANCHOR: JSONasString
partial def JSON.asString (val : JSON) : String :=
match val with
| true => "true"
| false => "false"
| null => "null"
| string s => "\"" ++ Lean.Json.escape s ++ "\""
| number n => dropDecimals n.toString
| object members =>
let memberToString mem :=
"\"" ++ Lean.Json.escape mem.fst ++ "\": " ++ asString mem.snd
"{" ++ ", ".separate (members.map memberToString) ++ "}"
| array elements =>
"[" ++ ", ".separate (elements.map asString) ++ "]"
-- ANCHOR_END: JSONasString
-- ANCHOR: Monoid
structure Monoid where
Carrier : Type
neutral : Carrier
op : Carrier → Carrier → Carrier
def natMulMonoid : Monoid :=
{ Carrier := Nat, neutral := 1, op := (· * ·) }
def natAddMonoid : Monoid :=
{ Carrier := Nat, neutral := 0, op := (· + ·) }
def stringMonoid : Monoid :=
{ Carrier := String, neutral := "", op := String.append }
def listMonoid (α : Type) : Monoid :=
{ Carrier := List α, neutral := [], op := List.append }
-- ANCHOR_END: Monoid
namespace MMM
-- ANCHOR: firstFoldMap
def foldMap (M : Monoid) (f : α → M.Carrier) (xs : List α) : M.Carrier :=
let rec go (soFar : M.Carrier) : List α → M.Carrier
| [] => soFar
| y :: ys => go (M.op soFar (f y)) ys
go M.neutral xs
-- ANCHOR_END: firstFoldMap
end MMM
-- ANCHOR: CoeMonoid
instance : CoeSort Monoid Type where
coe m := m.Carrier
-- ANCHOR_END: CoeMonoid
-- ANCHOR: foldMap
def foldMap (M : Monoid) (f : α → M) (xs : List α) : M :=
let rec go (soFar : M) : List α → M
| [] => soFar
| y :: ys => go (M.op soFar (f y)) ys
go M.neutral xs
-- ANCHOR_END: foldMap
-- ANCHOR: CoeBoolProp
instance : CoeSort Bool Prop where
coe b := b = true
-- ANCHOR_END: CoeBoolProp
namespace U
-- ANCHOR: CoeFun
class CoeFun (α : Type) (makeFunctionType : outParam (α → Type)) where
coe : (x : α) → makeFunctionType x
-- ANCHOR_END: CoeFun
end U
similar datatypes CoeFun U.CoeFun
-- ANCHOR: Adder
structure Adder where
howMuch : Nat
-- ANCHOR_END: Adder
-- ANCHOR: add5
def add5 : Adder := ⟨5⟩
-- ANCHOR_END: add5
/--
error: Function expected at
add5
but this term has type
Adder
Note: Expected a function because this term is being applied to the argument
3
-/
#check_msgs in
-- ANCHOR: add5notfun
#eval add5 3
-- ANCHOR_END: add5notfun
-- ANCHOR: CoeFunAdder
instance : CoeFun Adder (fun _ => Nat → Nat) where
coe a := (· + a.howMuch)
-- ANCHOR_END: CoeFunAdder
/-- info:
8
-/
#check_msgs in
-- ANCHOR: add53
#eval add5 3
-- ANCHOR_END: add53
namespace Ser
-- ANCHOR: Serializer
structure Serializer where
Contents : Type
serialize : Contents → JSON
-- ANCHOR_END: Serializer
-- ANCHOR: StrSer
def Str : Serializer :=
{ Contents := String,
serialize := JSON.string
}
-- ANCHOR_END: StrSer
-- ANCHOR: CoeFunSer
instance : CoeFun Serializer (fun s => s.Contents → JSON) where
coe s := s.serialize
-- ANCHOR_END: CoeFunSer
-- ANCHOR: buildResponse
def buildResponse (title : String) (R : Serializer)
(record : R.Contents) : JSON :=
JSON.object [
("title", JSON.string title),
("status", JSON.number 200),
("record", R record)
]
-- ANCHOR_END: buildResponse
/-- info:
JSON.object
[("title", JSON.string "Functional Programming in Lean"),
("status", JSON.number 200.000000),
("record", JSON.string "Programming is fun!")]
-/
#check_msgs in
-- ANCHOR: buildResponseOut
#eval buildResponse "Functional Programming in Lean" Str "Programming is fun!"
-- ANCHOR_END: buildResponseOut
/-- info:
"{\"title\": \"Functional Programming in Lean\", \"status\": 200, \"record\": \"Programming is fun!\"}"
-/
#check_msgs in
-- ANCHOR: buildResponseStr
#eval (buildResponse "Functional Programming in Lean" Str "Programming is fun!").asString
-- ANCHOR_END: buildResponseStr
end Ser
namespace A
/--
error: Application type mismatch: The argument
idahoSpiders
has type
NonEmptyList String
but is expected to have type
List ?m.3
in the application
List.getLast? idahoSpiders
-/
#check_msgs in
-- ANCHOR: lastSpiderB
def lastSpider :=
List.getLast? idahoSpiders
-- ANCHOR_END: lastSpiderB
discarding
/--
error: Invalid field `getLast?`: The environment does not contain `NonEmptyList.getLast?`
idahoSpiders
has type
NonEmptyList String
-/
#check_msgs in
-- ANCHOR: lastSpiderC
def lastSpider : Option String :=
idahoSpiders.getLast?
-- ANCHOR_END: lastSpiderC
stop discarding
-- ANCHOR: lastSpiderA
def lastSpider : Option String :=
List.getLast? idahoSpiders
-- ANCHOR_END: lastSpiderA
end A
instance : CoeDep (List α) (x :: xs) (NonEmptyList α) where
coe := ⟨x, xs⟩
-- ANCHOR: CoercionCycle
inductive A where
| a
inductive B where
| b
instance : Coe A B where
coe _ := B.b
instance : Coe B A where
coe _ := A.a
instance : Coe Unit A where
coe _ := A.a
def coercedToB : B := ()
-- ANCHOR_END: CoercionCycle
-- ANCHOR: ReprB
deriving instance Repr for B
-- ANCHOR_END: ReprB
-- ANCHOR: ReprBTm
example := Repr B
-- ANCHOR_END: ReprBTm
/-- info:
B.b
-/
#check_msgs in
-- ANCHOR: coercedToBEval
#eval coercedToB
-- ANCHOR_END: coercedToBEval
-- ANCHOR: CoePosNat
instance : Coe Pos Nat where
coe x := x.toNat
-- ANCHOR_END: CoePosNat
-- ANCHOR: posInt
def oneInt : Int := Pos.one
-- ANCHOR_END: posInt
/-- info:
[3, 4]
-/
#check_msgs in
-- ANCHOR: dropPosCoe
#eval [1, 2, 3, 4].drop (2 : Pos)
-- ANCHOR_END: dropPosCoe
/-- info:
List.drop (Pos.toNat 2) [1, 2, 3, 4] : List Nat
-/
#check_msgs in
-- ANCHOR: checkDropPosCoe
#check [1, 2, 3, 4].drop (2 : Pos)
-- ANCHOR_END: checkDropPosCoe
-- ANCHOR: trees
structure Tree : Type where
latinName : String
commonNames : List String
def oak : Tree :=
⟨"Quercus robur", ["common oak", "European oak"]⟩
def birch : Tree :=
{ latinName := "Betula pendula",
commonNames := ["silver birch", "warty birch"]
}
def sloe : Tree where
latinName := "Prunus spinosa"
commonNames := ["sloe", "blackthorn"]
-- ANCHOR_END: trees
-- ANCHOR: Display
class Display (α : Type) where
displayName : α → String
instance : Display Tree :=
⟨Tree.latinName⟩
instance : Display Tree :=
{ displayName := Tree.latinName }
instance : Display Tree where
displayName t := t.latinName
-- ANCHOR_END: Display
-- ANCHOR: birdExample
example : NonEmptyList String :=
{ head := "Sparrow",
tail := ["Duck", "Swan", "Magpie", "Eurasian coot", "Crow"]
}
-- ANCHOR_END: birdExample
-- ANCHOR: commAdd
example (n : Nat) (k : Nat) : Bool :=
n + k == k + n
-- ANCHOR_END: commAdd
-- ANCHOR: nats
example := [0,1,2,3,4,5,6,7,8,9,10]
-- ANCHOR_END: nats
-- ANCHOR: moreOps
section
example := [AndOp, OrOp, Inhabited]
example := Nat → List Int
example {α} := HAppend (List α) (NonEmptyList α) (NonEmptyList α)
end
-- ANCHOR_END: moreOps |
fp-lean/examples/Examples/Cat.lean | import ExampleSupport
namespace Str
-- ANCHOR: Stream
structure Stream where
flush : IO Unit
read : USize → IO ByteArray
write : ByteArray → IO Unit
getLine : IO String
putStr : String → IO Unit
isTty : BaseIO Bool
-- ANCHOR_END: Stream
end Str
similar datatypes Str.Stream IO.FS.Stream
namespace Original
def bufsize : USize := 20 * 1024
partial def dump (stream : IO.FS.Stream) : IO Unit := do
let buf ← stream.read bufsize
if buf.isEmpty then
pure ()
else
let stdout ← IO.getStdout
stdout.write buf
dump stream
def fileStream (filename : System.FilePath) : IO (Option IO.FS.Stream) := do
let fileExists ← filename.pathExists
if not fileExists then
let stderr ← IO.getStderr
stderr.putStrLn s!"File not found: {filename}"
pure none
else
let handle ← IO.FS.Handle.mk filename IO.FS.Mode.read
pure (some (IO.FS.Stream.ofHandle handle))
def process (exitCode : UInt32) (args : List String) : IO UInt32 := do
match args with
| [] => pure exitCode
| "-" :: args =>
let stdin ← IO.getStdin
dump stdin
process exitCode args
| filename :: args =>
let stream ← fileStream ⟨filename⟩
match stream with
| none =>
process 1 args
| some stream =>
dump stream
process exitCode args
def main (args : List String) : IO UInt32 :=
match args with
| [] => process 0 ["-"]
| _ => process 0 args
end Original
namespace Improved
def bufsize : USize := 20 * 1024
-- ANCHOR: dump
partial def dump (stream : IO.FS.Stream) : IO Unit := do
let buf ← stream.read bufsize
if buf.isEmpty then
pure ()
else
(← IO.getStdout).write buf
dump stream
-- ANCHOR_END: dump
-- ANCHOR: fileStream
def fileStream (filename : System.FilePath) : IO (Option IO.FS.Stream) := do
if not (← filename.pathExists) then
(← IO.getStderr).putStrLn s!"File not found: {filename}"
pure none
else
let handle ← IO.FS.Handle.mk filename IO.FS.Mode.read
pure (some (IO.FS.Stream.ofHandle handle))
-- ANCHOR_END: fileStream
-- ANCHOR: process
def process (exitCode : UInt32) (args : List String) : IO UInt32 := do
match args with
| [] => pure exitCode
| "-" :: args =>
dump (← IO.getStdin)
process exitCode args
| filename :: args =>
match (← fileStream ⟨filename⟩) with
| none =>
process 1 args
| some stream =>
dump stream
process exitCode args
-- ANCHOR_END: process
def main (args : List String) : IO UInt32 :=
match args with
| [] => process 0 ["-"]
| _ => process 0 args
end Improved
example : Original.bufsize = Improved.bufsize := by rfl
@[simp]
axiom dumpEquals : Original.dump = Improved.dump
@[simp]
theorem fileStreamEquals : Original.fileStream = Improved.fileStream := by rfl
@[simp]
theorem processEqual : Original.process = Improved.process := by
funext err args; revert err
induction args with
| nil =>
simp [Original.process, Improved.process]
| cons head tail ih =>
cases decEq head "-" <;> simp [*, ih, Original.process, Improved.process]
example : Original.main = Improved.main := by
funext x
simp [Original.main, Improved.main]
-- ANCHOR: getNumA
def getNumA : IO Nat := do
(← IO.getStdout).putStrLn "A"
pure 5
-- ANCHOR_END: getNumA
-- ANCHOR: getNumB
def getNumB : IO Nat := do
(← IO.getStdout).putStrLn "B"
pure 7
-- ANCHOR_END: getNumB
-- ANCHOR: getNums
def getNums (n : Nat) : IO (Nat × Nat) := do
(← IO.getStdout).putStrLn "Nums"
pure (n, n+n)
-- ANCHOR_END: getNums
/-- error:
invalid use of `(<- ...)`, must be nested inside a 'do' expression
-/
#check_msgs in
-- ANCHOR: testEffects
def test : IO Unit := do
let a : Nat := if (← getNumA) == 5 then 0 else (← getNumB)
(← IO.getStdout).putStrLn s!"The answer is {a}"
-- ANCHOR_END: testEffects
namespace Foo
-- ANCHOR: testEffectsExpanded
def test : IO Unit := do
let x ← getNumA
let y ← getNumB
let a : Nat := if x == 5 then 0 else y
(← IO.getStdout).putStrLn s!"The answer is {a}"
-- ANCHOR_END: testEffectsExpanded
end Foo
def a : IO Nat := do
pure ((← getNumA) + (← getNums (← getNumB)).snd)
def b : IO Nat := do
let x ← getNumA
let y ← getNumB
let z ← getNums y
pure (x + z.snd)
def c : IO Nat := do
let y ← getNumA
let x ← getNumB
let z ← getNums y
pure (x + z.snd)
def one : IO Nat := pure 1
def two : IO Nat := pure 2
namespace HelloName1
-- ANCHOR: helloOne
-- This version uses only whitespace-sensitive layout
def main : IO Unit := do
let stdin ← IO.getStdin
let stdout ← IO.getStdout
stdout.putStrLn "How would you like to be addressed?"
let name := (← stdin.getLine).trim
stdout.putStrLn s!"Hello, {name}!"
-- ANCHOR_END: helloOne
end HelloName1
namespace HelloName2
-- ANCHOR: helloTwo
-- This version is as explicit as possible
def main : IO Unit := do {
let stdin ← IO.getStdin;
let stdout ← IO.getStdout;
stdout.putStrLn "How would you like to be addressed?";
let name := (← stdin.getLine).trim;
stdout.putStrLn s!"Hello, {name}!"
}
-- ANCHOR_END: helloTwo
end HelloName2
namespace HelloName3
-- ANCHOR: helloThree
-- This version uses a semicolon to put two actions on the same line
def main : IO Unit := do
let stdin ← IO.getStdin; let stdout ← IO.getStdout
stdout.putStrLn "How would you like to be addressed?"
let name := (← stdin.getLine).trim
stdout.putStrLn s!"Hello, {name}!"
-- ANCHOR_END: helloThree
end HelloName3
open Nat (toFloat)
#eval toFloat 32 |
fp-lean/examples/Examples/ProgramsProofs.lean | |
fp-lean/examples/Examples/Induction.lean | import ExampleSupport
import Examples.Classes
import Examples.Monads.Conveniences
import Examples.DependentTypes.Pitfalls
namespace Tactical
discarding
/-- error:
unsolved goals
case zero
⊢ 0 = Nat.plusR 0 0
case succ
n✝ : Nat
a✝ : n✝ = Nat.plusR 0 n✝
⊢ n✝ + 1 = Nat.plusR 0 (n✝ + 1)
-/
#check_msgs in
-- ANCHOR: plusR_ind_zero_left_1
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k
-- ANCHOR_END: plusR_ind_zero_left_1
stop discarding
discarding
/--
error: unsolved goals
case zero
⊢ 0 = Nat.plusR 0 0
---
error: unsolved goals
case succ
n : Nat
ih : n = Nat.plusR 0 n
⊢ n + 1 = Nat.plusR 0 (n + 1)
-/
#check_msgs in
-- ANCHOR: plusR_ind_zero_left_2a
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => skip
| succ n ih => skip
-- ANCHOR_END: plusR_ind_zero_left_2a
stop discarding
discarding
/--
error: unsolved goals
case zero
⊢ 0 = Nat.plusR 0 0
---
error: unsolved goals
case succ
n : Nat
ih : n = Nat.plusR 0 n
⊢ n + 1 = Nat.plusR 0 (n + 1)
-/
#check_msgs in
-- ANCHOR: plusR_ind_zero_left_2b
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => skip
| succ n ih => skip
-- ANCHOR_END: plusR_ind_zero_left_2b
stop discarding
discarding
/--
error: unsolved goals
case zero
⊢ 0 = Nat.plusR 0 0
---
error: Too many variable names provided at alternative `succ`: 5 provided, but 2 expected
---
error: unsolved goals
case succ
n : Nat
ih : n = Nat.plusR 0 n
⊢ n + 1 = Nat.plusR 0 (n + 1)
-/
#check_msgs in
-- ANCHOR: plusR_ind_zero_left_3
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => skip
| succ n ih lots of names => skip
-- ANCHOR_END: plusR_ind_zero_left_3
stop discarding
discarding
/-- error:
unsolved goals
case succ
n : Nat
ih : n = Nat.plusR 0 n
⊢ n + 1 = Nat.plusR 0 (n + 1)
-/
#check_msgs in
-- ANCHOR: plusR_ind_zero_left_4
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih => skip
-- ANCHOR_END: plusR_ind_zero_left_4
stop discarding
discarding
/-- error:
unsolved goals
case succ
n : Nat
ih : n = Nat.plusR 0 n
⊢ n + 1 = Nat.plusR 0 n + 1
-/
#check_msgs in
-- ANCHOR: plusR_ind_zero_left_5
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
unfold Nat.plusR
-- ANCHOR_END: plusR_ind_zero_left_5
stop discarding
discarding
/-- error:
unsolved goals
case succ
n : Nat
ih : n = Nat.plusR 0 n
⊢ Nat.plusR 0 n + 1 = Nat.plusR 0 (Nat.plusR 0 n) + 1
-/
#check_msgs in
-- ANCHOR: plusR_ind_zero_left_6
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
unfold Nat.plusR
rw [ih]
-- ANCHOR_END: plusR_ind_zero_left_6
stop discarding
-- ANCHOR: plusR_zero_left_done
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
unfold Nat.plusR
rw [←ih]
-- ANCHOR_END: plusR_zero_left_done
namespace Golf
discarding
/-- error: `simp` made no progress -/
#check_msgs in
-- ANCHOR: plusR_zero_left_golf_1
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
simp
-- ANCHOR_END: plusR_zero_left_golf_1
stop discarding
discarding
/-- error:
unsolved goals
case succ
n : Nat
ih : n = Nat.plusR 0 n
⊢ n = Nat.plusR 0 n
-/
#check_msgs in
-- ANCHOR: plusR_zero_left_golf_2
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
simp [Nat.plusR]
-- ANCHOR_END: plusR_zero_left_golf_2
stop discarding
namespace One
-- ANCHOR: plusR_zero_left_golf_3
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
simp [Nat.plusR]
exact ih
-- ANCHOR_END: plusR_zero_left_golf_3
end One
namespace Two
-- ANCHOR: plusR_zero_left_golf_4
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
simp [Nat.plusR]
assumption
-- ANCHOR_END: plusR_zero_left_golf_4
end Two
namespace Three
-- ANCHOR: plusR_zero_left_golf_5
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k
case zero => rfl
case succ n ih =>
simp [Nat.plusR]
assumption
-- ANCHOR_END: plusR_zero_left_golf_5
end Three
discarding
/-- error:
unsolved goals
case succ
n✝ : Nat
a✝ : n✝ = Nat.plusR 0 n✝
⊢ n✝ = Nat.plusR 0 n✝
-/
#check_msgs in
-- ANCHOR: plusR_zero_left_golf_6a
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k <;> simp [Nat.plusR]
-- ANCHOR_END: plusR_zero_left_golf_6a
stop discarding
discarding
-- ANCHOR: plusR_zero_left_golf_6
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k <;> simp [Nat.plusR] <;> assumption
-- ANCHOR_END: plusR_zero_left_golf_6
stop discarding
-- ANCHOR: plusR_zero_left_golf_7
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k <;> grind [Nat.plusR]
-- ANCHOR_END: plusR_zero_left_golf_7
end Golf
discarding
/--
error: unsolved goals
case nil
α : Type u_1
⊢ [] ++ [] = []
---
error: unsolved goals
case cons
α : Type u_1
y : α
ys : List α
ih : ys ++ [] = ys
⊢ y :: ys ++ [] = y :: ys
-/
#check_msgs in
-- ANCHOR: append_nil_0b
theorem List.append_nil (xs : List α) : xs ++ [] = xs := by
induction xs with
| nil => skip
| cons y ys ih => skip
-- ANCHOR_END: append_nil_0b
stop discarding
discarding
/--
error: unsolved goals
case nil
α : Type u_1
⊢ [] ++ [] = []
---
error: unsolved goals
case cons
α : Type u_1
y : α
ys : List α
ih : ys ++ [] = ys
⊢ y :: ys ++ [] = y :: ys
-/
#check_msgs in
-- ANCHOR: append_nil_0a
theorem List.append_nil (xs : List α) : xs ++ [] = xs := by
induction xs with
| nil => skip
| cons y ys ih => skip
-- ANCHOR_END: append_nil_0a
stop discarding
theorem List.append_nil (xs : List α) : xs ++ [] = xs := by
induction xs with
| nil => rfl
| cons y ys ih =>
simp
theorem List.append_assoc (xs ys zs : List α) : xs ++ (ys ++ zs) = (xs ++ ys) ++ zs := by
induction xs <;> simp only [List.nil_append, List.cons_append, *]
end Tactical
-- ANCHOR: TreeCtors
example := @BinTree.leaf
example := @BinTree.branch
example {l : BinTree α} {x r} := BinTree.branch l x r
-- ANCHOR_END: TreeCtors
-- ANCHOR: BinTree_count
def BinTree.count : BinTree α → Nat
| .leaf => 0
| .branch l _ r =>
1 + l.count + r.count
-- ANCHOR_END: BinTree_count
discarding
/--
error: unsolved goals
case leaf
α : Type
⊢ leaf.mirror.count = leaf.count
---
error: unsolved goals
case branch
α : Type
l : BinTree α
x : α
r : BinTree α
ihl : l.mirror.count = l.count
ihr : r.mirror.count = r.count
⊢ (l.branch x r).mirror.count = (l.branch x r).count
-/
#check_msgs in
-- ANCHOR: mirror_count_0a
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => skip
| branch l x r ihl ihr => skip
-- ANCHOR_END: mirror_count_0a
stop discarding
discarding
/--
error: unsolved goals
case leaf
α : Type
⊢ leaf.mirror.count = leaf.count
---
error: unsolved goals
case branch
α : Type
l : BinTree α
x : α
r : BinTree α
ihl : l.mirror.count = l.count
ihr : r.mirror.count = r.count
⊢ (l.branch x r).mirror.count = (l.branch x r).count
-/
#check_msgs in
-- ANCHOR: mirror_count_0b
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => skip
| branch l x r ihl ihr => skip
-- ANCHOR_END: mirror_count_0b
stop discarding
discarding
/-- error:
unsolved goals
case branch
α : Type
l : BinTree α
x : α
r : BinTree α
ihl : l.mirror.count = l.count
ihr : r.mirror.count = r.count
⊢ (l.branch x r).mirror.count = (l.branch x r).count
-/
#check_msgs in
-- ANCHOR: mirror_count_1
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr => skip
-- ANCHOR_END: mirror_count_1
stop discarding
discarding
/-- error:
unsolved goals
case branch
α : Type
l : BinTree α
x : α
r : BinTree α
ihl : l.mirror.count = l.count
ihr : r.mirror.count = r.count
⊢ 1 + r.mirror.count + l.mirror.count = 1 + l.count + r.count
-/
#check_msgs in
-- ANCHOR: mirror_count_2
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr =>
simp [BinTree.mirror, BinTree.count]
-- ANCHOR_END: mirror_count_2
stop discarding
discarding
/-- error:
unsolved goals
case branch
α : Type
l : BinTree α
x : α
r : BinTree α
ihl : l.mirror.count = l.count
ihr : r.mirror.count = r.count
⊢ 1 + r.count + l.count = 1 + l.count + r.count
-/
#check_msgs in
-- ANCHOR: mirror_count_3
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr =>
simp [BinTree.mirror, BinTree.count]
rw [ihl, ihr]
-- ANCHOR_END: mirror_count_3
stop discarding
-- ANCHOR: mirror_count_4
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr =>
simp [BinTree.mirror, BinTree.count]
rw [ihl, ihr]
simp +arith
-- ANCHOR_END: mirror_count_4
namespace Golf
-- ANCHOR: mirror_count_5
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr =>
simp +arith [BinTree.mirror, BinTree.count, ihl, ihr]
-- ANCHOR_END: mirror_count_5
namespace B
-- ANCHOR: mirror_count_6
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr =>
simp +arith [BinTree.mirror, BinTree.count, *]
-- ANCHOR_END: mirror_count_6
end B
namespace A
discarding
-- ANCHOR: mirror_count_7
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t <;> simp +arith [BinTree.mirror, BinTree.count, *]
-- ANCHOR_END: mirror_count_7
stop discarding
-- ANCHOR: mirror_count_8
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t <;> grind [BinTree.mirror, BinTree.count]
-- ANCHOR_END: mirror_count_8
end A
end Golf
-- ANCHOR: others
example := Nat.zero = Nat.plusR 0 Nat.zero
example {A B : Nat} : Nat.succ A = Nat.succ B → A = B := by simp
example [Monad m] : m Unit := pure ()
example {n} := Nat.plusR 0 n
example {n} := Nat.plusR 0 n + 1
example {n} := Nat.plusR 0 (Nat.succ n)
-- ANCHOR_END: others
namespace Ex
-- ANCHOR: ex
theorem List.append_assoc (xs ys zs : List α) :
xs ++ (ys ++ zs) = (xs ++ ys) ++ zs := by simp
-- ANCHOR_END: ex
end Ex
def BinTree.graftLeft (root newBranch : BinTree α) : BinTree α :=
match root with
| .leaf => newBranch
| .branch l x r => .branch (l.graftLeft newBranch) x r
theorem BinTree.count_graftLeft_eq_sum_count' (root newBranch : BinTree α) :
(root.graftLeft newBranch).count = root.count + newBranch.count := by
induction root with
| leaf => simp [BinTree.graftLeft, BinTree.count]
| branch l x r ihl ihr =>
simp +arith [BinTree.graftLeft, BinTree.count, *]
theorem BinTree.count_graftLeft_eq_sum_count (root newBranch : BinTree α) :
(root.graftLeft newBranch).count = root.count + newBranch.count := by
induction root <;> grind [BinTree.graftLeft, BinTree.count] |
fp-lean/examples/Examples/HelloWorld.lean | import ExampleSupport
open SubVerso.Examples
-- ANCHOR: MainTypes
discarding
def main : IO Unit := pure ()
stop discarding
discarding
def main : IO UInt32 := pure 0
stop discarding
discarding
def main : List String → IO UInt32 := fun _ => pure 0
stop discarding
-- ANCHOR_END: MainTypes
/-- info:
"Hello"
-/
#check_msgs in
-- ANCHOR: dropBang
#eval "Hello!!!".dropRightWhile (· == '!')
-- ANCHOR_END: dropBang
/-- info:
"Hello"
-/
#check_msgs in
-- ANCHOR: dropNonLetter
#eval "Hello... ".dropRightWhile (fun c => not (c.isAlphanum))
-- ANCHOR_END: dropNonLetter
-- ANCHOR: twice
def twice (action : IO Unit) : IO Unit := do
action
action
-- ANCHOR_END: twice
%show_name twice as twice.name
/--
info: shy
shy
-/
#check_msgs in
-- ANCHOR: twiceShy
#eval twice (IO.println "shy")
-- ANCHOR_END: twiceShy
example := Nat.zero
example := Nat.succ
example := "Hello, David!"
example := "David"
example {α : Type} := IO α
-- ANCHOR: nTimes
def nTimes (action : IO Unit) : Nat → IO Unit
| 0 => pure ()
| n + 1 => do
action
nTimes action n
-- ANCHOR_END: nTimes
-- ANCHOR: nTimes3
#eval nTimes (IO.println "Hello") 3
-- ANCHOR_END: nTimes3
example : α → List α → List α := List.cons
-- ANCHOR: countdown
def countdown : Nat → List (IO Unit)
| 0 => [IO.println "Blast off!"]
| n + 1 => IO.println s!"{n + 1}" :: countdown n
-- ANCHOR_END: countdown
-- ANCHOR: from5
def from5 : List (IO Unit) := countdown 5
-- ANCHOR_END: from5
/-- info:
6
-/
#check_msgs in
-- ANCHOR: from5length
#eval from5.length
-- ANCHOR_END: from5length
-- ANCHOR: runActions
def runActions : List (IO Unit) → IO Unit
| [] => pure ()
| act :: actions => do
act
runActions actions
-- ANCHOR_END: runActions
-- ANCHOR: main
def main : IO Unit := runActions from5
-- ANCHOR_END: main
/--
info: 5
4
3
2
1
Blast off!
-/
#check_msgs in
-- ANCHOR: countdownFromFive
#eval main
-- ANCHOR_END: countdownFromFive
evaluation steps : IO Unit {{{ evalMain }}}
-- ANCHOR: evalMain
main
===>
runActions from5
===>
runActions (countdown 5)
===>
runActions
[IO.println "5",
IO.println "4",
IO.println "3",
IO.println "2",
IO.println "1",
IO.println "Blast off!"]
===>
do IO.println "5"
IO.println "4"
IO.println "3"
IO.println "2"
IO.println "1"
IO.println "Blast off!"
pure ()
-- ANCHOR_END: evalMain
end evaluation steps
/-- info:
3
2
1
Blast off!
-/
#check_msgs in
-- ANCHOR: evalDoesIO
#eval runActions (countdown 3)
-- ANCHOR_END: evalDoesIO
-- Verify claim in book made about guillemets. The following should work:
def «def» := 5
namespace Exercises
--ANCHOR: ExMain
def main : IO Unit := do
let englishGreeting := IO.println "Hello!"
IO.println "Bonjour!"
englishGreeting
--ANCHOR_END: ExMain
-- Part of a solution
/-- info:
Bonjour!
Hello!
-/
#check_msgs in
-- ANCHOR: unused
#eval main
-- ANCHOR_END: unused
end Exercises |
fp-lean/examples/Examples/DependentTypes.lean | import ExampleSupport
set_option linter.unusedVariables false
-- ANCHOR: natOrStringThree
def natOrStringThree (b : Bool) : if b then Nat else String :=
match b with
| true => (3 : Nat)
| false => "three"
-- ANCHOR_END: natOrStringThree
-- ANCHOR: Vect
inductive Vect (α : Type u) : Nat → Type u where
| nil : Vect α 0
| cons : α → Vect α n → Vect α (n + 1)
-- ANCHOR_END: Vect
deriving instance Repr for Vect
-- ANCHOR: vect3
example : Vect String 3 :=
.cons "one" (.cons "two" (.cons "three" .nil))
-- ANCHOR_END: vect3
/--
error: Type mismatch
Vect.nil
has type
Vect ?m.3 0
but is expected to have type
Vect String 3
-/
#check_msgs in
-- ANCHOR: nilNotLengthThree
example : Vect String 3 := Vect.nil
-- ANCHOR_END: nilNotLengthThree
/--
error: Type mismatch
Vect.nil
has type
Vect ?m.2 0
but is expected to have type
Vect String n
-/
#check_msgs in
-- ANCHOR: nilNotLengthN
example : Vect String n := Vect.nil
-- ANCHOR_END: nilNotLengthN
/--
error: Type mismatch
Vect.cons "Hello" (Vect.cons "world" Vect.nil)
has type
Vect String (0 + 1 + 1)
but is expected to have type
Vect String n
-/
#check_msgs in
-- ANCHOR: consNotLengthN
example : Vect String n := Vect.cons "Hello" (Vect.cons "world" Vect.nil)
-- ANCHOR_END: consNotLengthN
discarding
/-- error:
don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
⊢ Vect α n
-/
#check_msgs in
-- ANCHOR: replicateStart
def Vect.replicate (n : Nat) (x : α) : Vect α n := _
-- ANCHOR_END: replicateStart
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
k : Nat
⊢ Vect α (k + 1)
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
⊢ Vect α 0
-/
#check_msgs in
-- ANCHOR: replicateMatchOne
def Vect.replicate (n : Nat) (x : α) : Vect α n :=
match n with
| 0 => _
| k + 1 => _
-- ANCHOR_END: replicateMatchOne
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
k : Nat
⊢ Vect α (k + 1)
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
⊢ Vect α 0
-/
#check_msgs in
-- ANCHOR: replicateMatchTwo
def Vect.replicate (n : Nat) (x : α) : Vect α n :=
match n with
| 0 => _
| k + 1 => _
-- ANCHOR_END: replicateMatchTwo
stop discarding
discarding
/-- error:
don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
k : Nat
⊢ Vect α (k + 1)
-/
#check_msgs in
-- ANCHOR: replicateMatchThree
def Vect.replicate (n : Nat) (x : α) : Vect α n :=
match n with
| 0 => .nil
| k + 1 => _
-- ANCHOR_END: replicateMatchThree
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
k : Nat
⊢ Vect α k
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
k : Nat
⊢ α
-/
#check_msgs in
-- ANCHOR: replicateMatchFour
def Vect.replicate (n : Nat) (x : α) : Vect α n :=
match n with
| 0 => .nil
| k + 1 => .cons _ _
-- ANCHOR_END: replicateMatchFour
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
k : Nat
⊢ Vect α k
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
k : Nat
⊢ α
-/
#check_msgs in
-- ANCHOR: replicateMatchFive
def Vect.replicate (n : Nat) (x : α) : Vect α n :=
match n with
| 0 => .nil
| k + 1 => .cons _ _
-- ANCHOR_END: replicateMatchFive
stop discarding
discarding
/--
error: Application type mismatch: The argument
cons x (replicate k x)
has type
Vect α (k + 1)
but is expected to have type
Vect α k
in the application
cons x (cons x (replicate k x))
-/
#check_msgs in
-- ANCHOR: replicateOops
def Vect.replicate (n : Nat) (x : α) : Vect α n :=
match n with
| 0 => .nil
| k + 1 => .cons x (.cons x (replicate k x))
-- ANCHOR_END: replicateOops
stop discarding
-- ANCHOR: replicate
def Vect.replicate (n : Nat) (x : α) : Vect α n :=
match n with
| 0 => .nil
| k + 1 => .cons x (replicate k x)
-- ANCHOR_END: replicate
namespace Extras
-- ANCHOR: listReplicate
def List.replicate (n : Nat) (x : α) : List α :=
match n with
| 0 => []
| k + 1 => x :: x :: replicate k x
-- ANCHOR_END: listReplicate
end Extras
/-- info:
Vect.cons "hi" (Vect.cons "hi" (Vect.cons "hi" (Vect.nil)))
-/
#check_msgs in
-- ANCHOR: replicateHi
#eval Vect.replicate 3 "hi"
-- ANCHOR_END: replicateHi
-- ANCHOR: zip1
example : (
["Mount Hood",
"Mount Jefferson",
"South Sister"].zip ["Møllehøj", "Yding Skovhøj", "Ejer Bavnehøj"]
) = (
[("Mount Hood", "Møllehøj"),
("Mount Jefferson", "Yding Skovhøj"),
("South Sister", "Ejer Bavnehøj")]
) := rfl
-- ANCHOR_END: zip1
-- ANCHOR: zip2
example :
[3428.8, 3201, 3158.5, 3075, 3064].zip [170.86, 170.77, 170.35]
=
[(3428.8, 170.86), (3201, 170.77), (3158.5, 170.35)]
:= rfl
-- ANCHOR_END: zip2
-- ANCHOR: VectZip
def Vect.zip : Vect α n → Vect β n → Vect (α × β) n
| .nil, .nil => .nil
| .cons x xs, .cons y ys => .cons (x, y) (zip xs ys)
-- ANCHOR_END: VectZip
--ANCHOR: otherEx
example := Vect String 2
example := @Vect.nil
example := Except
example := Option
example := IO
example := Prop
example := Type 3
example := @List.zip
example := [1, 2, 3]
example := List String
example := 5
example := Nat.succ Nat.zero
--ANCHOR_END: otherEx
namespace Other
/--
error: Missing cases:
(List.cons _ _), []
[], (List.cons _ _)
-/
#check_msgs in
-- ANCHOR: zipMissing
def List.zip : List α → List β → List (α × β)
| [], [] => []
| x :: xs, y :: ys => (x, y) :: zip xs ys
-- ANCHOR_END: zipMissing
/--
error: Type mismatch
Vect.cons y ys
has type
Vect ?m.10 (?m.16 + 1)
but is expected to have type
Vect β 0
-/
#check_msgs in
-- ANCHOR: zipExtraCons
def Vect.zip : Vect α n → Vect β n → Vect (α × β) n
| .nil, .nil => .nil
| .nil, .cons y ys => .nil
| .cons x xs, .cons y ys => .cons (x, y) (zip xs ys)
-- ANCHOR_END: zipExtraCons
end Other
namespace Details
-- ANCHOR: VectZipLen
def Vect.zip : (n : Nat) → Vect α n → Vect β n → Vect (α × β) n
| 0, .nil, .nil => .nil
| k + 1, .cons x xs, .cons y ys => .cons (x, y) (zip k xs ys)
-- ANCHOR_END: VectZipLen
end Details
-- ANCHOR: exerciseDefs
def oregonianPeaks : Vect String 3 :=
.cons "Mount Hood" <|
.cons "Mount Jefferson" <|
.cons "South Sister" <| .nil
def danishPeaks : Vect String 3 :=
.cons "Møllehøj" <|
.cons "Yding Skovhøj" <|
.cons "Ejer Bavnehøj" <| .nil
def Vect.map : (α → β) → Vect α n → Vect β n
| f, .nil => .nil
| f, .cons x xs => .cons (f x) (xs.map f)
def Vect.zipWith : (α → β → γ) → Vect α n → Vect β n → Vect γ n
| f, .nil, .nil => .nil
| f, .cons x xs, .cons y ys => .cons (f x y) (xs.zipWith f ys)
def Vect.unzip : Vect (α × β) n → Vect α n × Vect β n
| .nil => (.nil, .nil)
| .cons (x, y) xys =>
let (xs, ys) := xys.unzip
(.cons x xs, .cons y ys)
def Vect.push : Vect α n → α → Vect α (n + 1)
| .nil, x => .cons x .nil
| .cons y ys, x => .cons y (push ys x)
def Vect.drop : (n : Nat) → Vect α (k + n) → Vect α k
| 0, xs => xs
| n + 1, .cons x xs => xs.drop n
def Vect.reverse : Vect α n → Vect α n
| .nil => .nil
| .cons x xs => xs.reverse.push x
-- ANCHOR: take
def Vect.take : (n : Nat) → Vect α (k + n) → Vect α n
| 0, xs => .nil
| n + 1, .cons x xs => .cons x (xs.take n)
-- ANCHOR_END: take
-- ANCHOR_END: exerciseDefs
/-- info:
Vect.cons
("Mount Hood", "Møllehøj")
(Vect.cons ("Mount Jefferson", "Yding Skovhøj") (Vect.cons ("South Sister", "Ejer Bavnehøj") (Vect.nil)))
-/
#check_msgs in
-- ANCHOR: peaksVectZip
#eval oregonianPeaks.zip danishPeaks
-- ANCHOR_END: peaksVectZip
/-- info:
Vect.cons "snowy" (Vect.cons "peaks" (Vect.nil))
-/
#check_msgs in
-- ANCHOR: snocSnowy
#eval Vect.push (.cons "snowy" .nil) "peaks"
-- ANCHOR_END: snocSnowy
/-- info:
Vect.cons "Ejer Bavnehøj" (Vect.nil)
-/
#check_msgs in
-- ANCHOR: ejerBavnehoej
#eval danishPeaks.drop 2
-- ANCHOR_END: ejerBavnehoej |
fp-lean/examples/Examples/MonadTransformers/Conveniences.lean | import ExampleSupport
#eval [3] |> List.reverse
namespace PipelineEx
variable (α : Type)
variable (β : Type)
variable (γ : Type)
variable (δ : Type)
variable (E₁ : α)
variable (E₂ : α → β)
variable (E₃ : β → γ)
variable (E₄ : γ → δ)
-- ANCHOR: pipelineShort
example : (
E₁ |> E₂
) = (
E₂ E₁
) := rfl
-- ANCHOR_END: pipelineShort
-- ANCHOR: pipeline
example : (
E₁ |> E₂ |> E₃ |> E₄
) = (
E₄ (E₃ (E₂ E₁))
) := rfl
-- ANCHOR_END: pipeline
/-- info:
"(some 5)"
-/
#check_msgs in
-- ANCHOR: some5
#eval some 5 |> toString
-- ANCHOR_END: some5
-- ANCHOR: times3
def times3 (n : Nat) : Nat := n * 3
-- ANCHOR_END: times3
/-- info:
"It is 15"
-/
#check_msgs in
-- ANCHOR: itIsFive
#eval 5 |> times3 |> toString |> ("It is " ++ ·)
-- ANCHOR_END: itIsFive
/-- info:
"It is 15"
-/
#check_msgs in
-- ANCHOR: itIsAlsoFive
#eval ("It is " ++ ·) <| toString <| times3 <| 5
-- ANCHOR_END: itIsAlsoFive
/-- info:
"It is 15"
-/
#check_msgs in
-- ANCHOR: itIsAlsoFiveParens
#eval ("It is " ++ ·) (toString (times3 5))
-- ANCHOR_END: itIsAlsoFiveParens
end PipelineEx
-- ANCHOR: listReverse
example : (
[1, 2, 3].reverse
) = (
List.reverse [1, 2, 3]
) := rfl
-- ANCHOR_END: listReverse
-- ANCHOR: listReverseDropReverse
example : (
([1, 2, 3].reverse.drop 1).reverse
) = (
[1, 2, 3] |> List.reverse |> List.drop 1 |> List.reverse
) := rfl
-- ANCHOR_END: listReverseDropReverse
-- ANCHOR: listReverseDropReversePipe
example : (
[1, 2, 3] |> List.reverse |> List.drop 1 |> List.reverse
) = (
[1, 2, 3] |>.reverse |>.drop 1 |>.reverse
) := rfl
-- ANCHOR_END: listReverseDropReversePipe
-- ANCHOR: spam
def spam : IO Unit := do
repeat IO.println "Spam!"
-- ANCHOR_END: spam
def bufsize : USize := 20 * 1024
-- ANCHOR: dump
def dump (stream : IO.FS.Stream) : IO Unit := do
let stdout ← IO.getStdout
repeat do
let buf ← stream.read bufsize
if buf.isEmpty then break
stdout.write buf
-- ANCHOR_END: dump
namespace More
-- ANCHOR: dumpWhile
def dump (stream : IO.FS.Stream) : IO Unit := do
let stdout ← IO.getStdout
let mut buf ← stream.read bufsize
while not buf.isEmpty do
stdout.write buf
buf ← stream.read bufsize
-- ANCHOR_END: dumpWhile
end More
-- ANCHOR: names
example := ForM
-- ANCHOR_END: names |
fp-lean/examples/Examples/MonadTransformers/Do.lean | import ExampleSupport
import Examples.MonadTransformers.Defs
import Examples.Monads.Many
import Examples.FunctorApplicativeMonad
set_option linter.unusedVariables false
namespace StEx
namespace FancyDo
-- ANCHOR: countLettersNoElse
def countLetters (str : String) : StateT LetterCounts (Except Err) Unit :=
let rec loop (chars : List Char) := do
match chars with
| [] => pure ()
| c :: cs =>
if c.isAlpha then
if vowels.contains c then
modify fun st => {st with vowels := st.vowels + 1}
else if consonants.contains c then
modify fun st => {st with consonants := st.consonants + 1}
else throw (.notALetter c)
loop cs
loop str.toList
-- ANCHOR_END: countLettersNoElse
end FancyDo
end StEx
namespace ThenDoUnless
-- ANCHOR: count
def count [Monad m] [MonadState Nat m] (p : α → m Bool) : List α → m Unit
| [] => pure ()
| x :: xs => do
if ← p x then
modify (· + 1)
count p xs
-- ANCHOR_END: count
-- ANCHOR: countNot
def countNot [Monad m] [MonadState Nat m] (p : α → m Bool) : List α → m Unit
| [] => pure ()
| x :: xs => do
unless ← p x do
modify (· + 1)
countNot p xs
-- ANCHOR_END: countNot
end ThenDoUnless
namespace EarlyReturn
namespace Non
-- ANCHOR: findHuhSimple
def List.find? (p : α → Bool) : List α → Option α
| [] => none
| x :: xs =>
if p x then
some x
else
find? p xs
-- ANCHOR_END: findHuhSimple
end Non
-- ANCHOR: findHuhFancy
def List.find? (p : α → Bool) : List α → Option α
| [] => failure
| x :: xs => do
if p x then return x
find? p xs
-- ANCHOR_END: findHuhFancy
-- ANCHOR: runCatch
def runCatch [Monad m] (action : ExceptT α m α) : m α := do
match ← action with
| Except.ok x => pure x
| Except.error x => pure x
-- ANCHOR_END: runCatch
namespace Desugared
-- ANCHOR: desugaredFindHuh
def List.find? (p : α → Bool) : List α → Option α
| [] => failure
| x :: xs =>
runCatch do
if p x then throw x else pure ()
monadLift (find? p xs)
-- ANCHOR_END: desugaredFindHuh
end Desugared
def List.lookup [BEq k] (key : k) : List (k × α) → Option α
| [] => failure
| x :: xs => do
if x.fst == key then return x.snd
lookup key xs
-- ANCHOR: greet
def greet (name : String) : String :=
"Hello, " ++ Id.run do return name
-- ANCHOR_END: greet
-- ANCHOR: greetDavid
example : (
greet "David"
) = (
"Hello, David"
) := rfl
-- ANCHOR_END: greetDavid
end EarlyReturn
-- ANCHOR: ManyForM
def Many.forM [Monad m] : Many α → (α → m PUnit) → m PUnit
| Many.none, _ => pure ()
| Many.more first rest, action => do
action first
forM (rest ()) action
instance : ForM m (Many α) α where
forM := Many.forM
-- ANCHOR_END: ManyForM
namespace Loops
namespace Fake
-- ANCHOR: ForM
class ForM (m : Type u → Type v) (γ : Type w₁)
(α : outParam (Type w₂)) where
forM [Monad m] : γ → (α → m PUnit) → m PUnit
-- ANCHOR_END: ForM
-- ANCHOR: ListForM
def List.forM [Monad m] : List α → (α → m PUnit) → m PUnit
| [], _ => pure ()
| x :: xs, action => do
action x
forM xs action
instance : ForM m (List α) α where
forM := List.forM
-- ANCHOR_END: ListForM
open StEx (vowels consonants Err LetterCounts)
-- ANCHOR: countLettersForM
def countLetters (str : String) : StateT LetterCounts (Except Err) Unit :=
forM str.toList fun c => do
if c.isAlpha then
if vowels.contains c then
modify fun st => {st with vowels := st.vowels + 1}
else if consonants.contains c then
modify fun st => {st with consonants := st.consonants + 1}
else throw (.notALetter c)
-- ANCHOR_END: countLettersForM
end Fake
-- ANCHOR: AllLessThan
structure AllLessThan where
num : Nat
-- ANCHOR_END: AllLessThan
-- ANCHOR: AllLessThanForM
def AllLessThan.forM [Monad m]
(coll : AllLessThan) (action : Nat → m Unit) :
m Unit :=
let rec countdown : Nat → m Unit
| 0 => pure ()
| n + 1 => do
action n
countdown n
countdown coll.num
instance : ForM m AllLessThan Nat where
forM := AllLessThan.forM
-- ANCHOR_END: AllLessThanForM
/-- info:
4
3
2
1
0
-/
#check_msgs in
-- ANCHOR: AllLessThanForMRun
#eval forM { num := 5 : AllLessThan } IO.println
-- ANCHOR_END: AllLessThanForMRun
-- ANCHOR: ForInIOAllLessThan
instance : ForIn m AllLessThan Nat where
forIn := ForM.forIn
-- ANCHOR_END: ForInIOAllLessThan
namespace Transformed
-- ANCHOR: OptionTExec
def OptionT.exec [Applicative m] (action : OptionT m α) : m Unit :=
action *> pure ()
-- ANCHOR_END: OptionTExec
-- ANCHOR: OptionTcountToThree
def countToThree (n : Nat) : IO Unit :=
let nums : AllLessThan := ⟨n⟩
OptionT.exec (forM nums fun i => do
if i < 3 then failure else IO.println i)
-- ANCHOR_END: OptionTcountToThree
/-- info:
6
5
4
3
-/
#check_msgs in
-- ANCHOR: optionTCountSeven
#eval countToThree 7
-- ANCHOR_END: optionTCountSeven
end Transformed
-- ANCHOR: countToThree
def countToThree (n : Nat) : IO Unit := do
let nums : AllLessThan := ⟨n⟩
for i in nums do
if i < 3 then break
IO.println i
-- ANCHOR_END: countToThree
/-- info:
6
5
4
3
-/
#check_msgs in
-- ANCHOR: countSevenFor
#eval countToThree 7
-- ANCHOR_END: countSevenFor
-- ANCHOR: parallelLoop
def parallelLoop := do
for x in ["currant", "gooseberry", "rowan"], y in [4:8] do
IO.println (x, y)
-- ANCHOR_END: parallelLoop
/-- info:
(currant, 4)
(gooseberry, 5)
(rowan, 6)
-/
#check_msgs in
-- ANCHOR: parallelLoopOut
#eval parallelLoop
-- ANCHOR_END: parallelLoopOut
-- ANCHOR: findHuh
def List.find? (p : α → Bool) (xs : List α) : Option α := do
for x in xs do
if p x then return x
failure
-- ANCHOR_END: findHuh
namespace Cont
-- ANCHOR: findHuhCont
def List.find? (p : α → Bool) (xs : List α) : Option α := do
for x in xs do
if not (p x) then continue
return x
failure
-- ANCHOR_END: findHuhCont
end Cont
example : List.find? p xs = Cont.List.find? p xs := by
induction xs <;> simp [List.find?, Cont.List.find?, bind]
-- ANCHOR: ListCount
def List.count (p : α → Bool) (xs : List α) : Nat := Id.run do
let mut found := 0
for x in xs do
if p x then found := found + 1
return found
-- ANCHOR_END: ListCount
end Loops
namespace Mut
-- ANCHOR: two
def two : Nat := Id.run do
let mut x := 0
x := x + 1
x := x + 1
return x
-- ANCHOR_END: two
example : two = 2 := by rfl
namespace St
-- ANCHOR: twoStateT
def two : Nat :=
let block : StateT Nat Id Nat := do
modify (· + 1)
modify (· + 1)
return (← get)
let (result, _finalState) := block 0
result
-- ANCHOR_END: twoStateT
example : two = 2 := by rfl
end St
-- ANCHOR: three
def three : Nat := Id.run do
let mut x := 0
for _ in [1, 2, 3] do
x := x + 1
return x
-- ANCHOR_END: three
example : three = 3 := by rfl
-- ANCHOR: six
def six : Nat := Id.run do
let mut x := 0
for y in [1, 2, 3] do
x := x + y
return x
-- ANCHOR_END: six
example : six = 6 := by rfl
/-- error:
`found` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intend to mutate but define `found`, consider using `let found` instead
-/
#check_msgs in
-- ANCHOR: nonLocalMut
def List.count (p : α → Bool) (xs : List α) : Nat := Id.run do
let mut found := 0
let rec go : List α → Id Unit
| [] => pure ()
| y :: ys => do
if p y then found := found + 1
go ys
return found
-- ANCHOR_END: nonLocalMut
end Mut
similar datatypes ForM Loops.Fake.ForM
namespace Ranges
deriving instance Repr for Std.Range
--NB in this section, using the typical bookExample macro fails
--because `stop` has become a reserved word due to another macro.
-- These tests are here in support of a table.
def rangeToList (r : Std.Range) : List Nat := Id.run do
let mut out : List Nat := []
for i in r do
out := out ++ [i]
pure out
/-- info:
{ start := 0, stop := 10, step := 1, step_pos := _ }
-/
#check_msgs in
-- ANCHOR: rangeStop
#eval [:10]
-- ANCHOR_END: rangeStop
/-- info:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-/
#check_msgs in
-- ANCHOR: rangeStopContents
#eval rangeToList [:10]
-- ANCHOR_END: rangeStopContents
/-- info:
{ start := 2, stop := 10, step := 1, step_pos := _ }
-/
#check_msgs in
-- ANCHOR: rangeStartStop
#eval [2:10]
-- ANCHOR_END: rangeStartStop
/-- info:
[2, 3, 4, 5, 6, 7, 8, 9]
-/
#check_msgs in
-- ANCHOR: rangeStartStopContents
#eval rangeToList [2:10]
-- ANCHOR_END: rangeStartStopContents
/-- info:
{ start := 0, stop := 10, step := 3, step_pos := _ }
-/
#check_msgs in
-- ANCHOR: rangeStopStep
#eval [:10:3]
-- ANCHOR_END: rangeStopStep
-- ANCHOR: ranges
example : Std.Range := [:10]
example : Std.Range := [2:10]
example : Std.Range := [:10:3]
example : Std.Range := [2:10:3]
example := [0, 10, 1, 2, 3]
example := IO.FS.Stream.getLine
-- ANCHOR_END: ranges
/-- info:
[0, 3, 6, 9]
-/
#check_msgs in
-- ANCHOR: rangeStopStepContents
#eval rangeToList [:10:3]
-- ANCHOR_END: rangeStopStepContents
/-- info:
{ start := 2, stop := 10, step := 3, step_pos := _ }
-/
#check_msgs in
-- ANCHOR: rangeStartStopStep
#eval [2:10:3]
-- ANCHOR_END: rangeStartStopStep
/-- info:
[2, 5, 8]
-/
#check_msgs in
-- ANCHOR: rangeStartStopStepContents
#eval rangeToList [2:10:3]
-- ANCHOR_END: rangeStartStopStepContents
-- ANCHOR: fourToEight
def fourToEight : IO Unit := do
for i in [4:9:2] do
IO.println i
-- ANCHOR_END: fourToEight
/-- info:
4
6
8
-/
#check_msgs in
-- ANCHOR: fourToEightOut
#eval fourToEight
-- ANCHOR_END: fourToEightOut
end Ranges
-- ANCHOR: printArray
def printArray [ToString α] (xs : Array α) : IO Unit := do
for h : i in [0:xs.size] do
IO.println s!"{i}:\t{xs[i]}"
-- ANCHOR_END: printArray
namespace SameDo
set_option linter.unusedVariables false
-- ANCHOR: sameBlock
example : Id Unit := do
let mut x := 0
x := x + 1
-- ANCHOR_END: sameBlock
-- ANCHOR: collapsedBlock
example : Id Unit := do
let mut x := 0
do x := x + 1
-- ANCHOR_END: collapsedBlock
/-- error:
`x` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intend to mutate but define `x`, consider using `let x` instead
-/
#check_msgs in
-- ANCHOR: letBodyNotBlock
example : Id Unit := do
let mut x := 0
let other := do
x := x + 1
other
-- ANCHOR_END: letBodyNotBlock
-- ANCHOR: letBodyArrBlock
example : Id Unit := do
let mut x := 0
let other ← do
x := x + 1
pure other
-- ANCHOR_END: letBodyArrBlock
/-- error:
`x` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intend to mutate but define `x`, consider using `let x` instead
-/
#check_msgs in
-- ANCHOR: funArgNotBlock
example : Id Unit := do
let mut x := 0
let addFour (y : Id Nat) := Id.run y + 4
addFour do
x := 5
-- ANCHOR_END: funArgNotBlock
-- ANCHOR: ifDoSame
example : Id Unit := do
let mut x := 0
if x > 2 then
x := x + 1
-- ANCHOR_END: ifDoSame
-- ANCHOR: ifDoDoSame
example : Id Unit := do
let mut x := 0
if x > 2 then do
x := x + 1
-- ANCHOR_END: ifDoDoSame
-- ANCHOR: matchDoSame
example : Id Unit := do
let mut x := 0
match true with
| true => x := x + 1
| false => x := 17
-- ANCHOR_END: matchDoSame
-- ANCHOR: matchDoDoSame
example : Id Unit := do
let mut x := 0
match true with
| true => do
x := x + 1
| false => do
x := 17
-- ANCHOR_END: matchDoDoSame
-- ANCHOR: doForSame
example : Id Unit := do
let mut x := 0
for y in [1:5] do
x := x + y
-- ANCHOR_END: doForSame
-- ANCHOR: doUnlessSame
example : Id Unit := do
let mut x := 0
unless 1 < 5 do
x := x + 1
-- ANCHOR_END: doUnlessSame
end SameDo |
fp-lean/examples/Examples/MonadTransformers/Defs.lean | import ExampleSupport
set_option linter.unusedVariables false
-- ANCHOR: various
example := Functor
example := @Functor.map
example := Monad
example := @HAdd.hAdd
example := semiOutParam
example := Id
-- ANCHOR_END: various
namespace Opt
-- ANCHOR: OptionTdef
def OptionT (m : Type u → Type v) (α : Type u) : Type v :=
m (Option α)
-- ANCHOR_END: OptionTdef
/--
error: Application type mismatch: The argument
some x
has type
Option α✝
but is expected to have type
α✝
in the application
pure (some x)
---
error: failed to synthesize
Pure (OptionT m)
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
---
error: Type mismatch
none
has type
Option ?m.24
but is expected to have type
α✝
---
error: failed to synthesize
Bind (OptionT m)
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: firstMonadOptionT
instance [Monad m] : Monad (OptionT m) where
pure x := pure (some x)
bind action next := do
match (← action) with
| none => pure none
| some v => next v
-- ANCHOR_END: firstMonadOptionT
namespace OneAttempt
-- ANCHOR: MonadOptionTAnnots
instance [Monad m] : Monad (OptionT m) where
pure x := (pure (some x) : m (Option _))
bind action next := (do
match (← action) with
| none => pure none
| some v => next v : m (Option _))
-- ANCHOR_END: MonadOptionTAnnots
end OneAttempt
namespace Structed
-- ANCHOR: OptionTStructure
structure OptionT (m : Type u → Type v) (α : Type u) : Type v where
run : m (Option α)
-- ANCHOR_END: OptionTStructure
-- ANCHOR: OptionTStructuredefs
example := @OptionT.mk
example := @OptionT.run
-- ANCHOR_END: OptionTStructuredefs
end Structed
-- ANCHOR: FakeStructOptionT
def OptionT.mk (x : m (Option α)) : OptionT m α := x
def OptionT.run (x : OptionT m α) : m (Option α) := x
-- ANCHOR_END: FakeStructOptionT
-- ANCHOR: MonadOptionTFakeStruct
instance [Monad m] : Monad (OptionT m) where
pure x := OptionT.mk (pure (some x))
bind action next := OptionT.mk do
match ← action with
| none => pure none
| some v => next v
-- ANCHOR_END: MonadOptionTFakeStruct
namespace Lawful
variable (α : Type)
variable (β : Type)
variable (γ : Type)
variable (m : Type → Type)
variable (v : α)
variable (w : m (Option α))
variable (f : α → OptionT m β)
variable (g : β → OptionT m γ)
variable [Monad m]
variable [LawfulMonad m]
equational steps {{{ OptionTFirstLaw }}}
-- ANCHOR: OptionTFirstLaw
bind (pure v) f
={ /-- Unfolding the definitions of `bind` and `pure` -/
by simp [bind, pure, OptionT.mk]
}=
OptionT.mk do
match ← pure (some v) with
| none => pure none
| some x => f x
={
/-- Desugaring nested action syntax -/
}=
OptionT.mk do
let y ← pure (some v)
match y with
| none => pure none
| some x => f x
={
/-- Desugaring `do`-notation -/
}=
OptionT.mk
(pure (some v) >>= fun y =>
match y with
| none => pure none
| some x => f x)
={
/-- Using the first monad rule for `m` -/
by simp [LawfulMonad.pure_bind (m := m)]
}=
OptionT.mk
(match some v with
| none => pure none
| some x => f x)
={
/-- Reduce `match` -/
}=
OptionT.mk (f v)
={
/-- Definition of `OptionT.mk` -/
}=
f v
-- ANCHOR_END: OptionTFirstLaw
stop equational steps
--ANCHOR: OptionTSecondLaw
example := bind w pure
example :=
OptionT.mk do
match ← w with
| none => pure none
| some v => pure (some v)
example := w >>= fun y => pure y
--ANCHOR_END: OptionTSecondLaw
--ANCHOR: OptionTThirdLaw
example {v} := bind (bind v f) g = bind v (fun x => bind (f x) g)
--ANCHOR_END: OptionTThirdLaw
end Lawful
-- ANCHOR: LiftOptionT
instance [Monad m] : MonadLift m (OptionT m) where
monadLift action := OptionT.mk do
pure (some (← action))
-- ANCHOR_END: LiftOptionT
-- ANCHOR: AlternativeOptionT
instance [Monad m] : Alternative (OptionT m) where
failure := OptionT.mk (pure none)
orElse x y := OptionT.mk do
match ← x with
| some result => pure (some result)
| none => y ()
-- ANCHOR_END: AlternativeOptionT
-- ANCHOR: getSomeInput
def getSomeInput : OptionT IO String := do
let input ← (← IO.getStdin).getLine
let trimmed := input.trim
if trimmed == "" then
failure
else pure trimmed
-- ANCHOR_END: getSomeInput
-- ANCHOR: UserInfo
structure UserInfo where
name : String
favoriteBeetle : String
-- ANCHOR_END: UserInfo
-- ANCHOR: getUserInfo
def getUserInfo : OptionT IO UserInfo := do
IO.println "What is your name?"
let name ← getSomeInput
IO.println "What is your favorite species of beetle?"
let beetle ← getSomeInput
pure ⟨name, beetle⟩
-- ANCHOR_END: getUserInfo
-- ANCHOR: interact
def interact : IO Unit := do
match ← getUserInfo with
| none =>
IO.eprintln "Missing info"
| some ⟨name, beetle⟩ =>
IO.println s!"Hello {name}, whose favorite beetle is {beetle}."
-- ANCHOR_END: interact
end Opt
namespace Ex
-- ANCHOR: ExceptT
def ExceptT (ε : Type u) (m : Type u → Type v) (α : Type u) : Type v :=
m (Except ε α)
-- ANCHOR_END: ExceptT
namespace Huh
-- ANCHOR: ExceptTNoUnis
def ExceptT.mk (x : m (Except ε α)) : ExceptT ε m α := x
-- ANCHOR_END: ExceptTNoUnis
/--
error: stuck at solving universe constraint
max ?u.10268 ?u.10269 =?= u
while trying to unify
ExceptT ε m α✝ : Type v
with
ExceptT.{max ?u.10269 ?u.10268, v} ε m α✝ : Type v
---
error: stuck at solving universe constraint
max ?u.10439 ?u.10440 =?= u
while trying to unify
ExceptT ε m β✝ : Type v
with
ExceptT.{max ?u.10440 ?u.10439, v} ε m β✝ : Type v
---
error: stuck at solving universe constraint
max ?u.10268 ?u.10269 =?= u
while trying to unify
ExceptT ε m α✝ : Type v
with
ExceptT.{max ?u.10269 ?u.10268, v} ε m α✝ : Type v
-/
#check_msgs in
-- ANCHOR: MonadMissingUni
instance {ε : Type u} {m : Type u → Type v} [Monad m] :
Monad (ExceptT ε m) where
pure x := ExceptT.mk (pure (Except.ok x))
bind result next := ExceptT.mk do
match (← result) with
| .error e => pure (.error e)
| .ok x => next x
-- ANCHOR_END: MonadMissingUni
end Huh
-- ANCHOR: ExceptTFakeStruct
def ExceptT.mk {ε α : Type u} (x : m (Except ε α)) : ExceptT ε m α := x
def ExceptT.run {ε α : Type u} (x : ExceptT ε m α) : m (Except ε α) := x
-- ANCHOR_END: ExceptTFakeStruct
-- ANCHOR: MonadExceptT
instance {ε : Type u} {m : Type u → Type v} [Monad m] :
Monad (ExceptT ε m) where
pure x := ExceptT.mk (pure (Except.ok x))
bind result next := ExceptT.mk do
match ← result with
| .error e => pure (.error e)
| .ok x => next x
-- ANCHOR_END: MonadExceptT
-- ANCHOR: ExceptTLiftExcept
instance [Monad m] : MonadLift (Except ε) (ExceptT ε m) where
monadLift action := ExceptT.mk (pure action)
-- ANCHOR_END: ExceptTLiftExcept
-- ANCHOR: ExceptTLiftM
instance [Monad m] : MonadLift m (ExceptT ε m) where
monadLift action := ExceptT.mk (.ok <$> action)
-- ANCHOR_END: ExceptTLiftM
namespace MyMonadExcept
-- ANCHOR: MonadExcept
class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where
throw : ε → m α
tryCatch : m α → (ε → m α) → m α
-- ANCHOR_END: MonadExcept
end MyMonadExcept
-- ANCHOR: ErrEx
inductive Err where
| divByZero
| notANumber : String → Err
-- ANCHOR_END: ErrEx
-- ANCHOR: divBackend
def divBackend [Monad m] [MonadExcept Err m] (n k : Int) : m Int :=
if k == 0 then
throw .divByZero
else pure (n / k)
-- ANCHOR_END: divBackend
-- ANCHOR: asNumber
def asNumber [Monad m] [MonadExcept Err m] (s : String) : m Int :=
match s.toInt? with
| none => throw (.notANumber s)
| some i => pure i
-- ANCHOR_END: asNumber
namespace Verbose
-- ANCHOR: divFrontend
def divFrontend [Monad m] [MonadExcept Err m] (n k : String) : m String :=
tryCatch (do pure (toString (← divBackend (← asNumber n) (← asNumber k))))
fun
| .divByZero => pure "Division by zero!"
| .notANumber s => pure s!"Not a number: \"{s}\""
-- ANCHOR_END: divFrontend
end Verbose
-- ANCHOR: divFrontendSugary
def divFrontend [Monad m] [MonadExcept Err m] (n k : String) : m String :=
try
pure (toString (← divBackend (← asNumber n) (← asNumber k)))
catch
| .divByZero => pure "Division by zero!"
| .notANumber s => pure s!"Not a number: \"{s}\""
-- ANCHOR_END: divFrontendSugary
example : @Verbose.divFrontend = @divFrontend := by rfl
-- ANCHOR: OptionExcept
example : MonadExcept Unit Option := inferInstance
-- ANCHOR_END: OptionExcept
end Ex
namespace St
-- ANCHOR: DefStateT
def StateT (σ : Type u)
(m : Type u → Type v) (α : Type u) : Type (max u v) :=
σ → m (α × σ)
-- ANCHOR_END: DefStateT
-- ANCHOR: MonadStateT
instance [Monad m] : Monad (StateT σ m) where
pure x := fun s => pure (x, s)
bind result next := fun s => do
let (v, s') ← result s
next v s'
-- ANCHOR_END: MonadStateT
instance [Monad m] : MonadStateOf σ (StateT σ m) where
get := fun s => pure (s, s)
set s' := fun _ => pure ((), s')
modifyGet f := fun s => pure (f s)
end St
namespace StEx
-- ANCHOR: countLetters
structure LetterCounts where
vowels : Nat
consonants : Nat
deriving Repr
inductive Err where
| notALetter : Char → Err
deriving Repr
def vowels :=
let lowerVowels := "aeiuoy"
lowerVowels ++ lowerVowels.map (·.toUpper)
def consonants :=
let lowerConsonants := "bcdfghjklmnpqrstvwxz"
lowerConsonants ++ lowerConsonants.map (·.toUpper )
def countLetters (str : String) : StateT LetterCounts (Except Err) Unit :=
let rec loop (chars : List Char) := do
match chars with
| [] => pure ()
| c :: cs =>
let st ← get
let st' ←
if c.isAlpha then
if vowels.contains c then
pure {st with vowels := st.vowels + 1}
else if consonants.contains c then
pure {st with consonants := st.consonants + 1}
else -- modified or non-English letter
pure st
else throw (.notALetter c)
set st'
loop cs
loop str.toList
-- ANCHOR_END: countLetters
namespace Modify
-- ANCHOR: countLettersModify
def countLetters (str : String) : StateT LetterCounts (Except Err) Unit :=
let rec loop (chars : List Char) := do
match chars with
| [] => pure ()
| c :: cs =>
if c.isAlpha then
if vowels.contains c then
modify fun st => {st with vowels := st.vowels + 1}
else if consonants.contains c then
modify fun st => {st with consonants := st.consonants + 1}
else -- modified or non-English letter
pure ()
else throw (.notALetter c)
loop cs
loop str.toList
-- ANCHOR_END: countLettersModify
-- ANCHOR: modify
def modify [MonadState σ m] (f : σ → σ) : m Unit :=
modifyGet fun s => ((), f s)
-- ANCHOR_END: modify
end Modify
namespace Reorder
-- ANCHOR: countLettersClassy
def countLetters [Monad m] [MonadState LetterCounts m] [MonadExcept Err m]
(str : String) : m Unit :=
let rec loop (chars : List Char) := do
match chars with
| [] => pure ()
| c :: cs =>
if c.isAlpha then
if vowels.contains c then
modify fun st => {st with vowels := st.vowels + 1}
else if consonants.contains c then
modify fun st => {st with consonants := st.consonants + 1}
else -- modified or non-English letter
pure ()
else throw (.notALetter c)
loop cs
loop str.toList
-- ANCHOR_END: countLettersClassy
-- ANCHOR: SomeMonads
abbrev M1 := StateT LetterCounts (ExceptT Err Id)
abbrev M2 := ExceptT Err (StateT LetterCounts Id)
-- ANCHOR_END: SomeMonads
-- ANCHOR: m
example := ReaderT
example := MonadReader
example := Except
example {α} := IO (Option α)
-- ANCHOR_END: m
-- ANCHOR: general
section
variable {T : (Type u → Type v) → Type u → Type v} {m : Type u → Type v} [Monad m] [Monad (T m)]
variable [MonadLift m (T m)]
example {α} := m α → T m α
example {α x} := (monadLift (pure x : m α)) = (pure x : T m α)
example {α x f} := monadLift (x >>= f : m α) = ((monadLift x : m α) >>= fun y => monadLift (f y) : T m α)
end
-- ANCHOR_END: general
/-- info:
Except.ok ((), { vowels := 2, consonants := 3 })
-/
#check_msgs in
-- ANCHOR: countLettersM1Ok
#eval countLetters (m := M1) "hello" ⟨0, 0⟩
-- ANCHOR_END: countLettersM1Ok
/-- info:
(Except.ok (), { vowels := 2, consonants := 3 })
-/
#check_msgs in
-- ANCHOR: countLettersM2Ok
#eval countLetters (m := M2) "hello" ⟨0, 0⟩
-- ANCHOR_END: countLettersM2Ok
/-- info:
Except.error (StEx.Err.notALetter '!')
-/
#check_msgs in
-- ANCHOR: countLettersM1Error
#eval countLetters (m := M1) "hello!" ⟨0, 0⟩
-- ANCHOR_END: countLettersM1Error
/-- info:
(Except.error (StEx.Err.notALetter '!'), { vowels := 2, consonants := 3 })
-/
#check_msgs in
-- ANCHOR: countLettersM2Error
#eval countLetters (m := M2) "hello!" ⟨0, 0⟩
-- ANCHOR_END: countLettersM2Error
-- ANCHOR: countWithFallback
def countWithFallback
[Monad m] [MonadState LetterCounts m] [MonadExcept Err m]
(str : String) : m Unit :=
try
countLetters str
catch _ =>
countLetters "Fallback"
-- ANCHOR_END: countWithFallback
/-- info:
Except.ok ((), { vowels := 2, consonants := 3 })
-/
#check_msgs in
-- ANCHOR: countWithFallbackM1Ok
#eval countWithFallback (m := M1) "hello" ⟨0, 0⟩
-- ANCHOR_END: countWithFallbackM1Ok
/-- info:
(Except.ok (), { vowels := 2, consonants := 3 })
-/
#check_msgs in
-- ANCHOR: countWithFallbackM2Ok
#eval countWithFallback (m := M2) "hello" ⟨0, 0⟩
-- ANCHOR_END: countWithFallbackM2Ok
/-- info:
Except.ok ((), { vowels := 2, consonants := 6 })
-/
#check_msgs in
-- ANCHOR: countWithFallbackM1Error
#eval countWithFallback (m := M1) "hello!" ⟨0, 0⟩
-- ANCHOR_END: countWithFallbackM1Error
/-- info:
(Except.ok (), { vowels := 4, consonants := 9 })
-/
#check_msgs in
-- ANCHOR: countWithFallbackM2Error
#eval countWithFallback (m := M2) "hello!" ⟨0, 0⟩
-- ANCHOR_END: countWithFallbackM2Error
variable (α : Type)
variable (σ : Type)
variable (σ' : Type)
-- ANCHOR: M1eval
example : (
M1 α
) = (
LetterCounts → Except Err (α × LetterCounts)
) := rfl
-- ANCHOR_END: M1eval
-- ANCHOR: M2eval
example : (
M2 α
) = (
LetterCounts → Except Err α × LetterCounts
) := rfl
-- ANCHOR_END: M2eval
-- ANCHOR: StateTDoubleA
example : (
StateT σ (StateT σ' Id) α
) = (
σ → σ' → ((α × σ) × σ')
) := rfl
-- ANCHOR_END: StateTDoubleA
-- ANCHOR: StateTDoubleB
example : (
StateT σ' (StateT σ Id) α
) = (
σ' → σ → ((α × σ') × σ)
) := rfl
-- ANCHOR_END: StateTDoubleB
end Reorder
namespace Cls
-- ANCHOR: MonadState
class MonadState (σ : outParam (Type u)) (m : Type u → Type v) :
Type (max (u+1) v) where
get : m σ
set : σ → m PUnit
modifyGet : (σ → α × σ) → m α
-- ANCHOR_END: MonadState
end Cls
example {σ m : _} [MonadStateOf σ m] : MonadState σ m := inferInstance
universe u
universe v
-- ANCHOR: getTheType
example : (σ : Type u) → {m : Type u → Type v} → [MonadStateOf σ m] → m σ := getThe
-- ANCHOR_END: getTheType
-- ANCHOR: modifyTheType
example :
(σ : Type u) → {m : Type u → Type v} → [MonadStateOf σ m] →
(σ → σ) → m PUnit
:= modifyThe
-- ANCHOR_END: modifyTheType
end StEx
similar datatypes MonadState StEx.Cls.MonadState |
fp-lean/examples/Examples/Classes/Even.lean | -- Example solution to the "even numbers" exercise, adapted from Chris Lovett's solution
namespace Even
inductive Even : Type where
| zero : Even
| plusTwo : Even → Even
def Even.plus : Even → Even → Even
| Even.zero, k => k
| Even.plusTwo n, k => Even.plusTwo (n.plus k)
instance : Add Even where
add := Even.plus
def eight : Even :=
Even.plusTwo (Even.plusTwo (Even.plusTwo (Even.plusTwo Even.zero)))
def two : Even :=
Even.plusTwo Even.zero
def Even.toNat : Even → Nat
| Even.zero => 0
| Even.plusTwo n => n.toNat + 2
instance : ToString Even where
toString x := toString (x.toNat)
#eval eight + two -- 10
#eval s!"There are {eight}"
def Even.mul : Even → Even → Even
| Even.zero, k => Even.zero
| Even.plusTwo Even.zero, k => k + k
| Even.plusTwo n, k => n.mul k + k + k
instance : Mul Even where
mul := Even.mul
#eval eight * two -- 16
instance : OfNat Even Nat.zero where
ofNat := Even.zero
instance [OfNat Even n] : OfNat Even (n + 2) where
ofNat := Even.plusTwo (OfNat.ofNat n)
#eval (2 : Even)
#eval (8 : Even) * 2 -- 16
end Even
namespace Old
inductive GEven : Nat → Type where
| zero : (m : Nat) → GEven m
| succ2 : {m : Nat} → GEven m → GEven m
example : GEven 1 := .zero 1
end Old
namespace New
inductive GEven (basis : Nat) : Nat → Type where
| base : basis % 2 = 0 → GEven basis basis
| plusTwo : GEven basis n → GEven basis (n + 2)
theorem geven_is_even (n : Nat) (even : GEven basis n) : n % 2 = 0 := by
induction even
case base => simp [*]
case plusTwo _ ih =>
have step (n : Nat) : (n + 2) % 2 = n % 2 := by
have : (n + 2) % 2 = if 0 < 2 ∧ 2 ≤ n + 2 then (n + 2 - 2) % 2 else n + 2 := Nat.mod_eq (n + 2) 2
have : 2 ≤ n + 2 := by simp
simp [*, Nat.add_sub_self_right n 2]
simp [*]
theorem geven_is_ge (n : Nat) (even : GEven basis n) : n ≥ basis := by
simp
induction even
case base => simp
case plusTwo _ ih =>
constructor; constructor; assumption
end New
namespace Other
inductive Even : Type where
| times2 : Nat → Even
deriving Repr
def Even.add : Even → Even → Even
| times2 a, times2 b => times2 (a + b)
instance : Add Even where
add := Even.add
instance : OfNat Even .zero where
ofNat := Even.times2 0
instance [OfNat Even n] : OfNat Even (n + 2) where
ofNat := OfNat.ofNat n + .times2 1
#eval (0 : Even)
#eval (22 : Even)
end Other |
fp-lean/examples/Examples/FunctorApplicativeMonad/ActualDefs.lean | import ExampleSupport
namespace F
-- ANCHOR: HonestFunctor
class Functor (f : Type u → Type v) : Type (max (u+1) v) where
map : {α β : Type u} → (α → β) → f α → f β
mapConst : {α β : Type u} → α → f β → f α :=
Function.comp map (Function.const _)
-- ANCHOR_END: HonestFunctor
namespace EEE
variable {α : Type}
variable {f : Type → Type}
variable {β : Type}
variable [inst : Functor f]
open Functor in
-- ANCHOR: unfoldCompConst
example : ((Function.comp map (Function.const _) : α → f β → f α) : (α → f β → f α)) = (fun (x : α) (y : f β) => map (fun _ => x) y : (α → f β → f α)) := rfl
-- ANCHOR_END: unfoldCompConst
end EEE
end F
-- ANCHOR: simpleConst
def simpleConst (x : α) (_ : β) : α := x
-- ANCHOR_END: simpleConst
#check simpleConst
/-- info:
["same", "same", "same"]
-/
#check_msgs in
-- ANCHOR: mapConst
#eval [1, 2, 3].map (simpleConst "same")
-- ANCHOR_END: mapConst
namespace F
/-- info:
Function.const.{u, v} {α : Sort u} (β : Sort v) (a : α) : β → α
-/
#check_msgs in
-- ANCHOR: FunctionConstType
#check Function.const
-- ANCHOR_END: FunctionConstType
end F
namespace F1
-- ANCHOR: FunctorSimplified
class Functor (f : Type u → Type v) : Type (max (u+1) v) where
map : {α β : Type u} → (α → β) → f α → f β
-- ANCHOR_END: FunctorSimplified
end F1
namespace F2
-- ANCHOR: FunctorDatatype
inductive Functor (f : Type u → Type v) : Type (max (u+1) v) where
| mk : ({α β : Type u} → (α → β) → f α → f β) → Functor f
-- ANCHOR_END: FunctorDatatype
end F2
namespace A
-- ANCHOR: Pure
class Pure (f : Type u → Type v) : Type (max (u+1) v) where
pure {α : Type u} : α → f α
-- ANCHOR_END: Pure
-- ANCHOR: Seq
class Seq (f : Type u → Type v) : Type (max (u+1) v) where
seq : {α β : Type u} → f (α → β) → (Unit → f α) → f β
-- ANCHOR_END: Seq
-- ANCHOR: SeqLeft
class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where
seqLeft : {α β : Type u} → f α → (Unit → f β) → f α
-- ANCHOR_END: SeqLeft
-- ANCHOR: SeqRight
class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where
seqRight : {α β : Type u} → f α → (Unit → f β) → f β
-- ANCHOR_END: SeqRight
-- ANCHOR: Applicative
class Applicative (f : Type u → Type v)
extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where
map := fun x y => Seq.seq (pure x) fun _ => y
seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b
seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b
-- ANCHOR_END: Applicative
namespace EEE
variable {α : Type}
variable {f : Type → Type}
variable {β : Type}
variable [inst : Applicative f]
-- ANCHOR: unfoldMapConstSeqLeft
example : (fun a b => Seq.seq (Functor.map (Function.const _) a) b : (f α → (Unit → f β) → f α)) = (fun a b => Seq.seq ((fun x _ => x) <$> a) b : (f α → (Unit → f β) → f α)) := rfl
-- ANCHOR_END: unfoldMapConstSeqLeft
-- ANCHOR: mapConstList
example : ((fun x _ => x) <$> [1, 2, 3] : (List (α → Nat))) = ([fun _ => 1, fun _ => 2, fun _ => 3] : (List (α → Nat))) := rfl
-- ANCHOR_END: mapConstList
-- ANCHOR: mapConstOption
example : ((fun x _ => x) <$> some "hello" : (Option (α → String))) = (some (fun _ => "hello") : (Option (α → String))) := rfl
-- ANCHOR_END: mapConstOption
evaluation steps : f α → (Unit → f β) → f β {{{ unfoldMapConstSeqRight }}}
-- ANCHOR: unfoldMapConstSeqRight
fun a b => Seq.seq (Functor.map (Function.const _ id) a) b
===>
fun a b => Seq.seq ((fun _ => id) <$> a) b
===>
fun a b => Seq.seq ((fun _ => fun x => x) <$> a) b
===>
fun a b => Seq.seq ((fun _ x => x) <$> a) b
-- ANCHOR_END: unfoldMapConstSeqRight
end evaluation steps
-- ANCHOR: mapConstIdList
example : ((fun _ x => x) <$> [1, 2, 3] : (List (β → β))) = ([fun x => x, fun x => x, fun x => x] : (List (β → β))) := rfl
-- ANCHOR_END: mapConstIdList
-- ANCHOR: mapConstIdOption
example : ((fun _ x => x) <$> some "hello" : (Option (β → β))) = (some (fun x => x) : (Option (β → β))) := rfl
-- ANCHOR_END: mapConstIdOption
end EEE
end A
namespace SeqLeftSugar
variable {f : Type → Type}
variable {α : Type}
variable {β : Type}
variable [inst : SeqLeft f]
variable {E1 : f α}
variable {E2 : f β}
-- ANCHOR: seqLeftSugar
example : E1 <* E2 = SeqLeft.seqLeft E1 (fun () => E2) := rfl
-- ANCHOR_END: seqLeftSugar
-- ANCHOR: seqLeftType
example : f α → (Unit → f β) → f α := SeqLeft.seqLeft
-- ANCHOR_END: seqLeftType
end SeqLeftSugar
similar datatypes Applicative A.Applicative
similar datatypes SeqLeft A.SeqLeft
similar datatypes Seq A.Seq
similar datatypes SeqRight A.SeqRight
similar datatypes Pure A.Pure
namespace M
-- ANCHOR: Bind
class Bind (m : Type u → Type v) where
bind : {α β : Type u} → m α → (α → m β) → m β
-- ANCHOR_END: Bind
-- ANCHOR: Monad
class Monad (m : Type u → Type v) : Type (max (u+1) v)
extends Applicative m, Bind m where
map f x := bind x (Function.comp pure f)
seq f x := bind f fun y => Functor.map y (x ())
seqLeft x y := bind x fun a => bind (y ()) (fun _ => pure a)
seqRight x y := bind x fun _ => y ()
-- ANCHOR_END: Monad
end M
similar datatypes Bind M.Bind
similar datatypes Monad M.Monad
-- ANCHOR: extras
example := Prop
example := Type
example := Type 1
example := Type 2
example : List Nat := [0, 17]
example := @List.map
-- ANCHOR_END: extras |
fp-lean/examples/Examples/DependentTypes/Finite.lean | import ExampleSupport
import Examples.Classes
-- ANCHOR: sundries
example := Type
example := Type 3
example := Prop
example := Empty
example := Option
example := Nat → Bool
example := @List.all
example := [true, false]
example {α} := Bool → α
-- ANCHOR_END: sundries
-- ANCHOR: NatOrBool
inductive NatOrBool where
| nat | bool
abbrev NatOrBool.asType (code : NatOrBool) : Type :=
match code with
| .nat => Nat
| .bool => Bool
-- ANCHOR_END: NatOrBool
-- ANCHOR: natOrBoolExamples
example := NatOrBool.nat.asType
example := NatOrBool.bool.asType
-- ANCHOR_END: natOrBoolExamples
-- ANCHOR: decode
def decode (t : NatOrBool) (input : String) : Option t.asType :=
match t with
| .nat => input.toNat?
| .bool =>
match input with
| "true" => some true
| "false" => some false
| _ => none
-- ANCHOR_END: decode
-- ANCHOR: NestedPairs
inductive NestedPairs where
| nat : NestedPairs
| pair : NestedPairs → NestedPairs → NestedPairs
abbrev NestedPairs.asType : NestedPairs → Type
| .nat => Nat
| .pair t1 t2 => asType t1 × asType t2
-- ANCHOR_END: NestedPairs
/--
error: failed to synthesize
BEq t.asType
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: beqNoCases
instance {t : NestedPairs} : BEq t.asType where
beq x y := x == y
-- ANCHOR_END: beqNoCases
-- ANCHOR: NestedPairsbeq
def NestedPairs.beq (t : NestedPairs) (x y : t.asType) : Bool :=
match t with
| .nat => x == y
| .pair t1 t2 => beq t1 x.fst y.fst && beq t2 x.snd y.snd
instance {t : NestedPairs} : BEq t.asType where
beq x y := t.beq x y
-- ANCHOR_END: NestedPairsbeq
-- ANCHOR: Finite
inductive Finite where
| unit : Finite
| bool : Finite
| pair : Finite → Finite → Finite
| arr : Finite → Finite → Finite
abbrev Finite.asType : Finite → Type
| .unit => Unit
| .bool => Bool
| .pair t1 t2 => asType t1 × asType t2
| .arr dom cod => asType dom → asType cod
-- ANCHOR_END: Finite
def Finite.count : Finite → Nat
| .unit => 1
| .bool => 2
| .pair t1 t2 => count t1 * count t2
| .arr dom cod => count cod ^ count dom
-- ANCHOR: ListProduct
def List.product (xs : List α) (ys : List β) : List (α × β) := Id.run do
let mut out : List (α × β) := []
for x in xs do
for y in ys do
out := (x, y) :: out
pure out.reverse
-- ANCHOR_END: ListProduct
def List.concatMap : List α → (α → List β) → List β
| [], _ => []
| x :: xs, f => f x ++ xs.concatMap f
namespace ListExtras
-- ANCHOR: foldr
def List.foldr (f : α → β → β) (default : β) : List α → β
| [] => default
| a :: l => f a (foldr f default l)
-- ANCHOR_END: foldr
end ListExtras
evaluation steps {{{ foldrSum }}}
-- ANCHOR: foldrSum
[1, 2, 3, 4, 5].foldr (· + ·) 0
===>
(1 :: 2 :: 3 :: 4 :: 5 :: []).foldr (· + ·) 0
===>
(1 + 2 + 3 + 4 + 5 + 0)
===>
15
-- ANCHOR_END: foldrSum
end evaluation steps
-- ANCHOR: MutualStart
mutual
-- ANCHOR: FiniteAll
def Finite.enumerate (t : Finite) : List t.asType :=
match t with
-- ANCHOR_END: MutualStart
| .unit => [()]
| .bool => [true, false]
| .pair t1 t2 => t1.enumerate.product t2.enumerate
| .arr dom cod => dom.functions cod.enumerate
-- ANCHOR_END: FiniteAll
-- ANCHOR: FiniteFunctions
-- ANCHOR: FiniteFunctionSigStart
def Finite.functions
(t : Finite)
(results : List α) : List (t.asType → α) :=
match t with
-- ANCHOR_END: FiniteFunctionSigStart
-- ANCHOR: FiniteFunctionUnit
| .unit =>
results.map fun r =>
fun () => r
-- ANCHOR_END: FiniteFunctionUnit
-- ANCHOR: FiniteFunctionBool
| .bool =>
(results.product results).map fun (r1, r2) =>
fun
| true => r1
| false => r2
-- ANCHOR_END: FiniteFunctionBool
-- ANCHOR: FiniteFunctionPair
| .pair t1 t2 =>
let f1s := t1.functions <| t2.functions results
f1s.map fun f =>
fun (x, y) =>
f x y
-- ANCHOR_END: FiniteFunctionPair
-- ANCHOR: MutualEnd
-- ANCHOR: FiniteFunctionArr
| .arr t1 t2 =>
let args := t1.enumerate
let base :=
results.map fun r =>
fun _ => r
args.foldr
(fun arg rest =>
(t2.functions rest).map fun more =>
fun f => more (f arg) f)
base
-- ANCHOR_END: FiniteFunctions
-- ANCHOR_END: FiniteFunctionArr
end
-- ANCHOR_END: MutualEnd
-- ANCHOR: FiniteBeq
def Finite.beq (t : Finite) (x y : t.asType) : Bool :=
match t with
| .unit => true
| .bool => x == y
| .pair t1 t2 => beq t1 x.fst y.fst && beq t2 x.snd y.snd
| .arr dom cod =>
dom.enumerate.all fun arg => beq cod (x arg) (y arg)
-- ANCHOR_END: FiniteBeq
theorem list_all_true : List.all xs (fun _ => true) = true := by
simp
theorem beq_refl (t : Finite) (x : t.asType) : t.beq x x = true := by
induction t with
| unit => simp [Finite.beq]
| bool => cases x <;> simp [Finite.beq]
| pair t1 t2 ih1 ih2 =>
simp [Finite.beq, *]
| arr t1 t2 ih1 ih2 =>
simp [Finite.beq, *]
def Finite.isSingleton : Finite → Bool
| .unit => true
| .bool => false
| .pair t1 t2 => not (isSingleton t1) || not (isSingleton t2)
| .arr _ cod => not (isSingleton cod)
def Finite.print : (t : Finite) → (x : t.asType) → String
| .unit, _ => "()"
| .bool, b => toString b
| .pair t1 t2, (x, y) => s!"({print t1 x}, {print t2 y})"
| .arr dom cod, f =>
let table := dom.enumerate |>.map fun x => s!"({print dom x} ↦ {print cod (f x)})"
"{" ++ ", ".separate table ++ "}"
def prop (t : Finite) : (Nat × Nat × Bool) := (t.enumerate.length, t.count, t.enumerate.length == t.count)
#eval prop (.arr .bool .unit)
#eval prop (.arr .bool (.pair .unit .bool))
#eval prop (.arr (.arr .bool (.pair (.arr .bool .unit) .bool)) (.pair .unit .bool))
#eval prop (.arr (.arr (.pair .bool .bool) .bool) .bool)
-- ANCHOR: lots
example : (.arr (.arr (.pair .bool .bool) .bool) .bool : Finite).asType = (((Bool × Bool) → Bool) → Bool) := rfl
-- ANCHOR_END: lots
/-- info:
65536
-/
#check_msgs in
-- ANCHOR: nestedFunLength
#eval Finite.enumerate (.arr (.arr (.pair .bool .bool) .bool) .bool) |>.length
-- ANCHOR_END: nestedFunLength
#eval Finite.enumerate (.arr .bool .unit) |>.map (Finite.print _)
#eval Finite.enumerate (.arr .bool .bool) |>.map (Finite.print _)
#eval Finite.enumerate (.arr (.arr .unit .bool) .bool) |>.map (Finite.print _)
/-- info:
true
-/
#check_msgs in
-- ANCHOR: arrBoolBoolEq
#eval Finite.beq (.arr .bool .bool) (fun _ => true) (fun b => b == b)
-- ANCHOR_END: arrBoolBoolEq
/-- info:
false
-/
#check_msgs in
-- ANCHOR: arrBoolBoolEq2
#eval Finite.beq (.arr .bool .bool) (fun _ => true) not
-- ANCHOR_END: arrBoolBoolEq2
/-- info:
true
-/
#check_msgs in
-- ANCHOR: arrBoolBoolEq3
#eval Finite.beq (.arr .bool .bool) id (not ∘ not)
-- ANCHOR_END: arrBoolBoolEq3 |
fp-lean/examples/Examples/DependentTypes/DB.lean | import ExampleSupport
import Examples.DependentTypes
set_option linter.unusedVariables false
-- ANCHOR: DBType
inductive DBType where
| int | string | bool
abbrev DBType.asType : DBType → Type
| .int => Int
| .string => String
| .bool => Bool
-- ANCHOR_END: DBType
/-- info:
"Mount Hood"
-/
#check_msgs in
-- ANCHOR: mountHoodEval
#eval ("Mount Hood" : DBType.string.asType)
-- ANCHOR_END: mountHoodEval
discarding
/--
error: failed to synthesize
BEq t.asType
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#check_msgs in
-- ANCHOR: dbEqNoSplit
def DBType.beq (t : DBType) (x y : t.asType) : Bool :=
x == y
-- ANCHOR_END: dbEqNoSplit
stop discarding
-- ANCHOR: dbEq
def DBType.beq (t : DBType) (x y : t.asType) : Bool :=
match t with
| .int => x == y
| .string => x == y
| .bool => x == y
-- ANCHOR_END: dbEq
-- ANCHOR: BEqDBType
instance {t : DBType} : BEq t.asType where
beq := t.beq
-- ANCHOR_END: BEqDBType
-- ANCHOR: BEqDBTypeCodes
instance : BEq DBType where
beq
| .int, .int => true
| .string, .string => true
| .bool, .bool => true
| _, _ => false
-- ANCHOR_END: BEqDBTypeCodes
-- ANCHOR: ReprAsType
instance {t : DBType} : Repr t.asType where
reprPrec :=
match t with
| .int => reprPrec
| .string => reprPrec
| .bool => reprPrec
-- ANCHOR_END: ReprAsType
-- ANCHOR: Schema
structure Column where
name : String
contains : DBType
abbrev Schema := List Column
-- ANCHOR_END: Schema
-- ANCHOR: Row
abbrev Row : Schema → Type
| [] => Unit
| [col] => col.contains.asType
| col1 :: col2 :: cols => col1.contains.asType × Row (col2::cols)
-- ANCHOR_END: Row
-- ANCHOR: RowStuck
example (c cs) := Row (c :: cs)
-- ANCHOR_END: RowStuck
-- ANCHOR: Naturals
section
example := Nat
open Nat
example := succ
example := zero
end
-- ANCHOR_END: Naturals
-- ANCHOR: Table
abbrev Table (s : Schema) := List (Row s)
-- ANCHOR_END: Table
-- ANCHOR: peak
abbrev peak : Schema := [
⟨"name", .string⟩,
⟨"location", .string⟩,
⟨"elevation", .int⟩,
⟨"lastVisited", .int⟩
]
-- ANCHOR_END: peak
-- ANCHOR: mountainDiary
def mountainDiary : Table peak := [
("Mount Nebo", "USA", 3637, 2013),
("Moscow Mountain", "USA", 1519, 2015),
("Himmelbjerget", "Denmark", 147, 2004),
("Mount St. Helens", "USA", 2549, 2010)
]
-- ANCHOR_END: mountainDiary
-- ANCHOR: waterfall
abbrev waterfall : Schema := [
⟨"name", .string⟩,
⟨"location", .string⟩,
⟨"lastVisited", .int⟩
]
-- ANCHOR_END: waterfall
-- ANCHOR: waterfallDiary
def waterfallDiary : Table waterfall := [
("Multnomah Falls", "USA", 2018),
("Shoshone Falls", "USA", 2014)
]
-- ANCHOR_END: waterfallDiary
discarding
/--
error: Type mismatch
(v1, r1')
has type
?m.10 × ?m.11
but is expected to have type
Row (col :: cols)
-/
#check_msgs in
-- ANCHOR: RowBEqRecursion
def Row.bEq (r1 r2 : Row s) : Bool :=
match s with
| [] => true
| col::cols =>
match r1, r2 with
| (v1, r1'), (v2, r2') =>
v1 == v2 && bEq r1' r2'
-- ANCHOR_END: RowBEqRecursion
stop discarding
-- ANCHOR: RowBEq
def Row.bEq (r1 r2 : Row s) : Bool :=
match s with
| [] => true
| [_] => r1 == r2
| _::_::_ =>
match r1, r2 with
| (v1, r1'), (v2, r2') =>
v1 == v2 && bEq r1' r2'
instance : BEq (Row s) where
beq := Row.bEq
-- ANCHOR_END: RowBEq
-- ANCHOR: HasCol
inductive HasCol : Schema → String → DBType → Type where
| here : HasCol (⟨name, t⟩ :: _) name t
| there : HasCol s name t → HasCol (_ :: s) name t
-- ANCHOR_END: HasCol
-- ANCHOR: peakElevationInt
example : HasCol peak "elevation" .int := .there (.there .here)
-- ANCHOR_END: peakElevationInt
-- ANCHOR: Rowget
def Row.get (row : Row s) (col : HasCol s n t) : t.asType :=
match s, col, row with
| [_], .here, v => v
| _::_::_, .here, (v, _) => v
| _::_::_, .there next, (_, r) => get r next
-- ANCHOR_END: Rowget
-- ANCHOR: Subschema
inductive Subschema : Schema → Schema → Type where
| nil : Subschema [] bigger
| cons :
HasCol bigger n t →
Subschema smaller bigger →
Subschema (⟨n, t⟩ :: smaller) bigger
-- ANCHOR_END: Subschema
-- ANCHOR: SubschemaNames
example := @Subschema.nil
example := @Subschema.cons
example := @HasCol.there
example := @HasCol.here
example := HasCol peak "location" DBType.string
example := Subschema peak []
-- ANCHOR_END: SubschemaNames
-- ANCHOR: travelDiary
abbrev travelDiary : Schema :=
[⟨"name", .string⟩, ⟨"location", .string⟩, ⟨"lastVisited", .int⟩]
-- ANCHOR_END: travelDiary
-- ANCHOR: peakDiarySub
example : Subschema travelDiary peak :=
.cons .here
(.cons (.there .here)
(.cons (.there (.there (.there .here))) .nil))
-- ANCHOR_END: peakDiarySub
-- ANCHOR: emptySub
example : Subschema [] peak := by constructor
-- ANCHOR_END: emptySub
/-- error:
unsolved goals
case a
⊢ HasCol peak "location" DBType.string
case a
⊢ Subschema [] peak
-/
#check_msgs in
-- ANCHOR: notDone
example : Subschema [⟨"location", .string⟩] peak := by constructor
-- ANCHOR_END: notDone
/-- error:
unsolved goals
case a.a
⊢ HasCol
[{ name := "location", contains := DBType.string }, { name := "elevation", contains := DBType.int },
{ name := "lastVisited", contains := DBType.int }]
"location" DBType.string
case a
⊢ Subschema [] peak
-/
#check_msgs in
-- ANCHOR: notDone2
example : Subschema [⟨"location", .string⟩] peak := by
constructor
constructor
-- ANCHOR_END: notDone2
/-- error:
unsolved goals
case a
⊢ Subschema [] peak
-/
#check_msgs in
-- ANCHOR: notDone3
example : Subschema [⟨"location", .string⟩] peak := by
constructor
constructor
constructor
-- ANCHOR_END: notDone3
-- ANCHOR: notDone4
example : Subschema [⟨"location", .string⟩] peak := by
constructor
constructor
constructor
constructor
-- ANCHOR_END: notDone4
-- ANCHOR: notDone5
example : Subschema [⟨"location", .string⟩] peak :=
.cons (.there .here) .nil
-- ANCHOR_END: notDone5
-- ANCHOR: notDone6
example : Subschema [⟨"location", .string⟩] peak := by repeat constructor
-- ANCHOR_END: notDone6
-- ANCHOR: subschemata
example : Subschema travelDiary peak := by repeat constructor
example : Subschema travelDiary waterfall := by repeat constructor
-- ANCHOR_END: subschemata
-- ANCHOR: SubschemaAdd
def Subschema.addColumn :
Subschema smaller bigger →
Subschema smaller (c :: bigger)
| .nil => .nil
| .cons col sub' => .cons (.there col) sub'.addColumn
-- ANCHOR_END: SubschemaAdd
-- ANCHOR: SubschemaSame
def Subschema.reflexive : (s : Schema) → Subschema s s
| [] => .nil
| _ :: cs => .cons .here (reflexive cs).addColumn
-- ANCHOR_END: SubschemaSame
-- ANCHOR: addVal
def addVal (v : c.contains.asType) (row : Row s) : Row (c :: s) :=
match s, row with
| [], () => v
| c' :: cs, v' => (v, v')
-- ANCHOR_END: addVal
-- ANCHOR: RowProj
def Row.project (row : Row s) : (s' : Schema) → Subschema s' s → Row s'
| [], .nil => ()
| [_], .cons c .nil => row.get c
| _::_::_, .cons c cs => (row.get c, row.project _ cs)
-- ANCHOR_END: RowProj
-- ANCHOR: DBExpr
inductive DBExpr (s : Schema) : DBType → Type where
| col (n : String) (loc : HasCol s n t) : DBExpr s t
| eq (e1 e2 : DBExpr s t) : DBExpr s .bool
| lt (e1 e2 : DBExpr s .int) : DBExpr s .bool
| and (e1 e2 : DBExpr s .bool) : DBExpr s .bool
| const : t.asType → DBExpr s t
-- ANCHOR_END: DBExpr
namespace Fake
-- ANCHOR: tallDk
def tallInDenmark : DBExpr peak .bool :=
.and (.lt (.const 1000) (.col "elevation" (by repeat constructor)))
(.eq (.col "location" (by repeat constructor)) (.const "Denmark"))
-- ANCHOR_END: tallDk
end Fake
-- ANCHOR: cBang
macro "c!" n:term : term => `(DBExpr.col $n (by repeat constructor))
-- ANCHOR_END: cBang
-- ANCHOR: tallDkBetter
def tallInDenmark : DBExpr peak .bool :=
.and (.lt (.const 1000) (c! "elevation"))
(.eq (c! "location") (.const "Denmark"))
-- ANCHOR_END: tallDkBetter
-- ANCHOR: DBExprEval
def DBExpr.evaluate (row : Row s) : DBExpr s t → t.asType
| .col _ loc => row.get loc
| .eq e1 e2 => evaluate row e1 == evaluate row e2
| .lt e1 e2 => evaluate row e1 < evaluate row e2
| .and e1 e2 => evaluate row e1 && evaluate row e2
| .const v => v
-- ANCHOR_END: DBExprEval
-- ANCHOR: DBExprEvalType
example : Row s → DBExpr s t → t.asType := DBExpr.evaluate
-- ANCHOR_END: DBExprEvalType
/-- info:
false
-/
#check_msgs in
-- ANCHOR: valbybakke
#eval tallInDenmark.evaluate ("Valby Bakke", "Denmark", 31, 2023)
-- ANCHOR_END: valbybakke
/-- info:
true
-/
#check_msgs in
-- ANCHOR: fakeDkBjerg
#eval tallInDenmark.evaluate ("Fictional mountain", "Denmark", 1230, 2023)
-- ANCHOR_END: fakeDkBjerg
/-- info:
false
-/
#check_msgs in
-- ANCHOR: borah
#eval tallInDenmark.evaluate ("Mount Borah", "USA", 3859, 1996)
-- ANCHOR_END: borah
-- ANCHOR: disjoint
def disjoint [BEq α] (xs ys : List α) : Bool :=
not (xs.any ys.contains || ys.any xs.contains)
-- ANCHOR_END: disjoint
-- ANCHOR: renameColumn
def Schema.renameColumn : (s : Schema) → HasCol s n t → String → Schema
| c :: cs, .here, n' => {c with name := n'} :: cs
| c :: cs, .there next, n' => c :: renameColumn cs next n'
-- ANCHOR_END: renameColumn
-- ANCHOR: Query
inductive Query : Schema → Type where
| table : Table s → Query s
| union : Query s → Query s → Query s
| diff : Query s → Query s → Query s
| select : Query s → DBExpr s .bool → Query s
| project :
Query s → (s' : Schema) →
Subschema s' s →
Query s'
| product :
Query s1 → Query s2 →
disjoint (s1.map Column.name) (s2.map Column.name) →
Query (s1 ++ s2)
| renameColumn :
Query s → (c : HasCol s n t) → (n' : String) →
!((s.map Column.name).contains n') →
Query (s.renameColumn c n')
| prefixWith :
(n : String) → Query s →
Query (s.map fun c => {c with name := n ++ "." ++ c.name})
-- ANCHOR_END: Query
-- ANCHOR: RowAppend
def Row.append (r1 : Row s1) (r2 : Row s2) : Row (s1 ++ s2) :=
match s1, r1 with
| [], () => r2
| [_], v => addVal v r2
| _::_::_, (v, r') => (v, r'.append r2)
-- ANCHOR_END: RowAppend
namespace Mine
-- ANCHOR: ListFlatMap
def List.flatMap (f : α → List β) : (xs : List α) → List β
| [] => []
| x :: xs => f x ++ xs.flatMap f
-- ANCHOR_END: ListFlatMap
end Mine
-- ANCHOR: TableCartProd
def Table.cartesianProduct (table1 : Table s1) (table2 : Table s2) :
Table (s1 ++ s2) :=
table1.flatMap fun r1 => table2.map r1.append
-- ANCHOR_END: TableCartProd
namespace OrElse
-- ANCHOR: TableCartProdOther
def Table.cartesianProduct (table1 : Table s1) (table2 : Table s2) :
Table (s1 ++ s2) := Id.run do
let mut out : Table (s1 ++ s2) := []
for r1 in table1 do
for r2 in table2 do
out := (r1.append r2) :: out
pure out.reverse
-- ANCHOR_END: TableCartProdOther
end OrElse
-- ANCHOR: filterA
example : (
["Willamette", "Columbia", "Sandy", "Deschutes"].filter (·.length > 8)
) = (
["Willamette", "Deschutes"]
) := rfl
-- ANCHOR_END: filterA
-- ANCHOR: ListWithout
def List.without [BEq α] (source banned : List α) : List α :=
source.filter fun r => !(banned.contains r)
-- ANCHOR_END: ListWithout
-- ANCHOR: renameRow
def Row.rename (c : HasCol s n t) (row : Row s) :
Row (s.renameColumn c n') :=
match s, row, c with
| [_], v, .here => v
| _::_::_, (v, r), .here => (v, r)
| _::_::_, (v, r), .there next => addVal v (r.rename next)
-- ANCHOR_END: renameRow
-- ANCHOR: prefixRow
def prefixRow (row : Row s) :
Row (s.map fun c => {c with name := n ++ "." ++ c.name}) :=
match s, row with
| [], _ => ()
| [_], v => v
| _::_::_, (v, r) => (v, prefixRow r)
-- ANCHOR_END: prefixRow
-- ANCHOR: QueryExec
def Query.exec : Query s → Table s
| .table t => t
| .union q1 q2 => exec q1 ++ exec q2
| .diff q1 q2 => exec q1 |>.without (exec q2)
-- ANCHOR: selectCase
| .select q e => exec q |>.filter e.evaluate
-- ANCHOR_END: selectCase
| .project q _ sub => exec q |>.map (·.project _ sub)
| .product q1 q2 _ => exec q1 |>.cartesianProduct (exec q2)
| .renameColumn q c _ _ => exec q |>.map (·.rename c)
| .prefixWith _ q => exec q |>.map prefixRow
-- ANCHOR_END: QueryExec
-- ANCHOR: Query1
open Query in
def example1 :=
table mountainDiary |>.select
(.lt (.const 500) (c! "elevation")) |>.project
[⟨"elevation", .int⟩] (by repeat constructor)
-- ANCHOR_END: Query1
/-- info:
[3637, 1519, 2549]
-/
#check_msgs in
-- ANCHOR: Query1Exec
#eval example1.exec
-- ANCHOR_END: Query1Exec
-- ANCHOR: Query2
open Query in
def example2 :=
let mountain := table mountainDiary |>.prefixWith "mountain"
let waterfall := table waterfallDiary |>.prefixWith "waterfall"
mountain.product waterfall (by decide)
|>.select (.eq (c! "mountain.location") (c! "waterfall.location"))
|>.project [⟨"mountain.name", .string⟩, ⟨"waterfall.name", .string⟩]
(by repeat constructor)
-- ANCHOR_END: Query2
/-- info:
[("Mount Nebo", "Multnomah Falls"), ("Mount Nebo", "Shoshone Falls"), ("Moscow Mountain", "Multnomah Falls"),
("Moscow Mountain", "Shoshone Falls"), ("Mount St. Helens", "Multnomah Falls"),
("Mount St. Helens", "Shoshone Falls")]
-/
#check_msgs in
-- ANCHOR: Query2Exec
#eval example2.exec
-- ANCHOR_END: Query2Exec
namespace Ooops
discarding
/--
error: unsolved goals
mountains : Query (List.map (fun c => { name := "mountain" ++ "." ++ c.name, contains := c.contains }) peak) :=
prefixWith "mountain" (table mountainDiary)
waterfalls : Query (List.map (fun c => { name := "waterfall" ++ "." ++ c.name, contains := c.contains }) waterfall) :=
prefixWith "waterfall" (table waterfallDiary)
⊢ disjoint ["mountain.name", "mountain.location", "mountain.elevation", "mountain.lastVisited"]
["waterfall.name", "waterfall.location", "waterfall.lastVisited"] =
true
---
error: unsolved goals
case a.a.a.a.a.a.a
mountains : Query (List.map (fun c => { name := "mountain" ++ "." ++ c.name, contains := c.contains }) peak) := ⋯
waterfalls : Query (List.map (fun c => { name := "waterfall" ++ "." ++ c.name, contains := c.contains }) waterfall) := ⋯
⊢ HasCol (List.map (fun c => { name := "waterfall" ++ "." ++ c.name, contains := c.contains }) []) "location" ?m.62066
-/
#check_msgs in
-- ANCHOR: QueryOops1
open Query in
def example2 :=
let mountains := table mountainDiary |>.prefixWith "mountain"
let waterfalls := table waterfallDiary |>.prefixWith "waterfall"
mountains.product waterfalls (by simp)
|>.select (.eq (c! "location") (c! "waterfall.location"))
|>.project [⟨"mountain.name", .string⟩, ⟨"waterfall.name", .string⟩]
(by repeat constructor)
-- ANCHOR_END: QueryOops1
stop discarding
/--
error: Tactic `decide` proved that the proposition
disjoint (List.map Column.name peak) (List.map Column.name waterfall) = true
is false
---
error: unsolved goals
case a.a.a.a.a.a.a
mountains : Query peak := ⋯
waterfalls : Query waterfall := ⋯
⊢ HasCol [] "mountain.location" ?m.29
---
error: unsolved goals
case a.a.a.a.a.a.a
mountains : Query peak := ⋯
waterfalls : Query waterfall := ⋯
⊢ HasCol [] "waterfall.location" ?m.29
---
error: unsolved goals
case a.a.a.a.a.a.a.a
mountains : Query peak := ⋯
waterfalls : Query waterfall := ⋯
⊢ HasCol [] "mountain.name" DBType.string
case a
mountains : Query peak := ⋯
waterfalls : Query waterfall := ⋯
⊢ Subschema [{ name := "waterfall.name", contains := DBType.string }] (peak ++ waterfall)
-/
#check_msgs in
-- ANCHOR: QueryOops2
open Query in
def example2 :=
let mountains := table mountainDiary
let waterfalls := table waterfallDiary
mountains.product waterfalls (by decide)
|>.select (.eq (c! "mountain.location") (c! "waterfall.location"))
|>.project [⟨"mountain.name", .string⟩, ⟨"waterfall.name", .string⟩]
(by repeat constructor)
-- ANCHOR_END: QueryOops2
end Ooops
#eval (by repeat constructor : Nat)
#eval (by repeat constructor : List Nat)
#eval (by repeat constructor : Vect Nat 4)
#eval (by repeat constructor : Row [⟨"price", .int⟩])
#eval (by repeat constructor : Row peak)
deriving instance Repr for HasCol
#eval (by repeat constructor : HasCol [⟨"price", .int⟩, ⟨"price", .int⟩] "price" .int)
-- ANCHOR: nullable
structure NDBType where
underlying : DBType
nullable : Bool
abbrev NDBType.asType (t : NDBType) : Type :=
if t.nullable then
Option t.underlying.asType
else
t.underlying.asType
-- ANCHOR_END: nullable
-- ANCHOR: misc
example := List Bool
example := false
example := true
example := Prop
example := @List.filter
example := @List.map
section
variable {smaller bigger : Schema}
example := Subschema smaller bigger
example := (smaller, bigger)
end
example := [List Nat, Vect Nat 4, Row [], Row [⟨"price", .int⟩], Row peak, HasCol [⟨"price", .int⟩, ⟨"price", .int⟩] "price" .int]
-- ANCHOR_END: misc
discarding
-- ANCHOR: ListMonad
instance : Monad List where
pure x := [x]
bind xs f := List.flatMap f xs
-- ANCHOR_END: ListMonad
stop discarding |
fp-lean/examples/Examples/DependentTypes/Pitfalls.lean | import ExampleSupport
import Examples.DependentTypes
set_option linter.unusedVariables false
-- ANCHOR: plusL
def Nat.plusL : Nat → Nat → Nat
| 0, k => k
| n + 1, k => plusL n k + 1
-- ANCHOR_END: plusL
-- ANCHOR: plusR
def Nat.plusR : Nat → Nat → Nat
| n, 0 => n
| n, k + 1 => plusR n k + 1
-- ANCHOR_END: plusR
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n k n✝ : Nat
x : α
xs : Vect α n✝
ys : Vect α k
⊢ Vect α ((n✝ + 1).plusL k)
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
ys : Vect α k
⊢ Vect α (Nat.plusL 0 k)
-/
#check_msgs in
-- ANCHOR: appendL1
def appendL : Vect α n → Vect α k → Vect α (n.plusL k)
| .nil, ys => _
| .cons x xs, ys => _
-- ANCHOR_END: appendL1
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n k n✝ : Nat
x : α
xs : Vect α n✝
ys : Vect α k
⊢ Vect α ((n✝ + 1).plusL k)
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
ys : Vect α k
⊢ Vect α (Nat.plusL 0 k)
-/
#check_msgs in
-- ANCHOR: appendL2
def appendL : Vect α n → Vect α k → Vect α (n.plusL k)
| .nil, ys => _
| .cons x xs, ys => _
-- ANCHOR_END: appendL2
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
x : α
xs : Vect α n
ys : Vect α k
⊢ Vect α ((n + 1).plusL k)
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
k : Nat
ys : Vect α k
⊢ Vect α (Nat.plusL 0 k)
-/
#check_msgs in
-- ANCHOR: appendL3
def appendL : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusL k)
| 0, k, .nil, ys => _
| n + 1, k, .cons x xs, ys => _
-- ANCHOR_END: appendL3
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
x : α
xs : Vect α n
ys : Vect α k
⊢ Vect α ((n + 1).plusL k)
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
k : Nat
ys : Vect α k
⊢ Vect α (Nat.plusL 0 k)
-/
#check_msgs in
-- ANCHOR: appendL4
def appendL : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusL k)
| 0, k, .nil, ys => _
| n + 1, k, .cons x xs, ys => _
-- ANCHOR_END: appendL4
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
x : α
xs : Vect α n
ys : Vect α k
⊢ Vect α (n.plusL k + 1)
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
k : Nat
ys : Vect α k
⊢ Vect α k
-/
#check_msgs in
-- ANCHOR: appendL5
def appendL : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusL k)
| 0, k, .nil, ys => (_ : Vect α k)
| n + 1, k, .cons x xs, ys => (_ : Vect α (n.plusL k + 1))
-- ANCHOR_END: appendL5
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
x : α
xs : Vect α n
ys : Vect α k
⊢ Vect α (n.plusL k + 1)
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
k : Nat
ys : Vect α k
⊢ Vect α k
-/
#check_msgs in
-- ANCHOR: appendL6
def appendL : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusL k)
| 0, k, .nil, ys => (_ : Vect α k)
| n + 1, k, .cons x xs, ys => (_ : Vect α (n.plusL k + 1))
-- ANCHOR_END: appendL6
stop discarding
discarding
/-- error:
don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
x : α
xs : Vect α n
ys : Vect α k
⊢ Vect α (n.plusL k + 1)
-/
#check_msgs in
-- ANCHOR: appendL7
def appendL : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusL k)
| 0, k, .nil, ys => ys
| n + 1, k, .cons x xs, ys => (_ : Vect α (n.plusL k + 1))
-- ANCHOR_END: appendL7
stop discarding
discarding
/-- error:
don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
x : α
xs : Vect α n
ys : Vect α k
⊢ Vect α (n.plusL k)
-/
#check_msgs in
-- ANCHOR: appendL8
def appendL : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusL k)
| 0, k, .nil, ys => ys
| n + 1, k, .cons x xs, ys => .cons x (_ : Vect α (n.plusL k))
-- ANCHOR_END: appendL8
stop discarding
namespace Almost
-- ANCHOR: appendL9
def appendL : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusL k)
| 0, k, .nil, ys => ys
| n + 1, k, .cons x xs, ys => .cons x (appendL n k xs ys)
-- ANCHOR_END: appendL9
end Almost
-- ANCHOR: appendL
def appendL : Vect α n → Vect α k → Vect α (n.plusL k)
| .nil, ys => ys
| .cons x xs, ys => .cons x (appendL xs ys)
-- ANCHOR_END: appendL
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
x : α
xs : Vect α n
ys : Vect α k
⊢ Vect α ((n + 1).plusR k)
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
k : Nat
ys : Vect α k
⊢ Vect α (Nat.plusR 0 k)
-/
#check_msgs in
-- ANCHOR: appendR1
def appendR : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusR k)
| 0, k, .nil, ys => _
| n + 1, k, .cons x xs, ys => _
-- ANCHOR_END: appendR1
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
x : α
xs : Vect α n
ys : Vect α k
⊢ Vect α ((n + 1).plusR k)
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
k : Nat
ys : Vect α k
⊢ Vect α (Nat.plusR 0 k)
-/
#check_msgs in
-- ANCHOR: appendR2
def appendR : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusR k)
| 0, k, .nil, ys => _
| n + 1, k, .cons x xs, ys => _
-- ANCHOR_END: appendR2
stop discarding
discarding
/--
error: Type mismatch
?m.11
has type
Vect α k
but is expected to have type
Vect α (Nat.plusR 0 k)
-/
#check_msgs in
-- ANCHOR: appendR3
def appendR : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusR k)
| 0, k, .nil, ys => (_ : Vect α k)
| n + 1, k, .cons x xs, ys => _
-- ANCHOR_END: appendR3
stop discarding
discarding
/--
error: Type mismatch
?m.15
has type
Vect α k
but is expected to have type
Vect α (0 + k)
-/
#check_msgs in
-- ANCHOR: appendR4
def appendR : (n k : Nat) → Vect α n → Vect α k → Vect α (n + k)
| 0, k, .nil, ys => (_ : Vect α k)
| n + 1, k, .cons x xs, ys => _
-- ANCHOR_END: appendR4
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
k : Nat
⊢ k + 1 = Nat.plusR 0 (k + 1)
---
error: don't know how to synthesize placeholder
context:
⊢ 0 = Nat.plusR 0 0
-/
#check_msgs in
-- ANCHOR: plusR_zero_left1
def plusR_zero_left : (k : Nat) → k = Nat.plusR 0 k
| 0 => _
| k + 1 => _
-- ANCHOR_END: plusR_zero_left1
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
k : Nat
⊢ k + 1 = Nat.plusR 0 (k + 1)
---
error: don't know how to synthesize placeholder
context:
⊢ 0 = Nat.plusR 0 0
-/
#check_msgs in
-- ANCHOR: plusR_zero_left2
def plusR_zero_left : (k : Nat) → k = Nat.plusR 0 k
| 0 => _
| k + 1 => _
-- ANCHOR_END: plusR_zero_left2
stop discarding
discarding
/-- error:
don't know how to synthesize placeholder
context:
k : Nat
⊢ k + 1 = Nat.plusR 0 (k + 1)
-/
#check_msgs in
-- ANCHOR: plusR_zero_left3
def plusR_zero_left : (k : Nat) → k = Nat.plusR 0 k
| 0 => by rfl
| k + 1 => _
-- ANCHOR_END: plusR_zero_left3
stop discarding
namespace Adding
axiom k : Nat
-- ANCHOR: plusRStep
example : (
Nat.plusR 0 k + 1
) = (
Nat.plusR 0 (k + 1)
) := rfl
-- ANCHOR_END: plusRStep
end Adding
discarding
/-- error:
don't know how to synthesize placeholder
context:
k : Nat
⊢ k + 1 = Nat.plusR 0 k + 1
-/
#check_msgs in
-- ANCHOR: plusR_zero_left4
def plusR_zero_left : (k : Nat) → k = Nat.plusR 0 k
| 0 => by rfl
| k + 1 => (_ : k + 1 = Nat.plusR 0 k + 1)
-- ANCHOR_END: plusR_zero_left4
stop discarding
discarding
-- ANCHOR: plusR_zero_left_done
def plusR_zero_left : (k : Nat) → k = Nat.plusR 0 k
| 0 => by rfl
| k + 1 =>
congrArg (· + 1) (plusR_zero_left k)
-- ANCHOR_END: plusR_zero_left_done
stop discarding
-- ANCHOR: plusR_zero_left_thm
theorem plusR_zero_left : (k : Nat) → k = Nat.plusR 0 k
| 0 => by rfl
| k + 1 =>
congrArg (· + 1) (plusR_zero_left k)
-- ANCHOR_END: plusR_zero_left_thm
discarding
/--
error: don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
x : α
xs : Vect α n
ys : Vect α k
⊢ Vect α ((n + 1).plusR k)
---
error: don't know how to synthesize placeholder
context:
α : Type u_1
k : Nat
ys : Vect α k
⊢ Vect α k
-/
#check_msgs in
-- ANCHOR: appendRsubst
def appendR : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusR k)
| 0, k, .nil, ys => plusR_zero_left k ▸ (_ : Vect α k)
| n + 1, k, .cons x xs, ys => _
-- ANCHOR_END: appendRsubst
stop discarding
discarding
/-- error:
don't know how to synthesize placeholder
context:
α : Type u_1
n k : Nat
x : α
xs : Vect α n
ys : Vect α k
⊢ Vect α ((n + 1).plusR k)
-/
#check_msgs in
-- ANCHOR: appendR5
def appendR : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusR k)
| 0, k, .nil, ys => plusR_zero_left k ▸ ys
| n + 1, k, .cons x xs, ys => _
-- ANCHOR_END: appendR5
stop discarding
discarding
/-- error:
don't know how to synthesize placeholder
context:
n k : Nat
⊢ (n + 1).plusR (k + 1) = n.plusR (k + 1) + 1
-/
#check_msgs in
-- ANCHOR: plusR_succ_left_0
theorem plusR_succ_left (n : Nat) :
(k : Nat) → Nat.plusR (n + 1) k = Nat.plusR n k + 1
| 0 => by rfl
| k + 1 => _
-- ANCHOR_END: plusR_succ_left_0
stop discarding
discarding
/-- error:
don't know how to synthesize placeholder
context:
n k : Nat
⊢ (n + 1).plusR (k + 1) = n.plusR (k + 1) + 1
-/
#check_msgs in
-- ANCHOR: plusR_succ_left_2
theorem plusR_succ_left (n : Nat) :
(k : Nat) → Nat.plusR (n + 1) k = Nat.plusR n k + 1
| 0 => by rfl
| k + 1 => _
-- ANCHOR_END: plusR_succ_left_2
stop discarding
-- ANCHOR: plusR_succ_left
theorem plusR_succ_left (n : Nat) :
(k : Nat) → Nat.plusR (n + 1) k = Nat.plusR n k + 1
| 0 => by rfl
| k + 1 => congrArg (· + 1) (plusR_succ_left n k)
-- ANCHOR_END: plusR_succ_left
-- ANCHOR: appendR
def appendR : (n k : Nat) → Vect α n → Vect α k → Vect α (n.plusR k)
| 0, k, .nil, ys =>
plusR_zero_left k ▸ ys
| n + 1, k, .cons x xs, ys =>
plusR_succ_left n k ▸ .cons x (appendR n k xs ys)
-- ANCHOR_END: appendR
namespace Impl
-- ANCHOR: appendRImpl
def appendR : Vect α n → Vect α k → Vect α (n.plusR k)
| .nil, ys => plusR_zero_left _ ▸ ys
| .cons x xs, ys => plusR_succ_left _ _ ▸ .cons x (appendR xs ys)
-- ANCHOR_END: appendRImpl
end Impl
def plusRAdd (n : Nat) : (k : Nat) → n.plusR k = n + k
| 0 => by rfl
| k + 1 => congrArg (· + 1) (plusRAdd n k)
-- ANCHOR: moreNames
example : (
-- ANCHOR: moreFun
(n : Nat) → Vect String n
-- ANCHOR_END: moreFun
) = (
(k : Nat) → Vect String k
) := rfl
-- ANCHOR: againFun
example := (n : Nat) → Vect String (Nat.plusL 0 n)
-- ANCHOR_END: againFun
-- ANCHOR: stuckFun
example := (n : Nat) → Vect String (Nat.plusL n 0)
-- ANCHOR_END: stuckFun
example := List String
example : List Nat := [5, 3, 1]
example := (n k : Nat) → Vect Int n
example := (n k : Nat) → Vect Int k
example : (Vect String (1 + 4)) = (Vect String (3 + 2)) := rfl
example := 5
example := 17
example := 33
example := ["a", "b"] ++ ["c"]
example := List Nat
example := Int
example := List
example := @List.append
section
open List
example := @nil
example := @cons
end
section
open Nat
variable (k : Nat)
example := plusL 0 k
example := zero
example := succ
end
example {α} {k} := (Vect α (Nat.plusL 0 k)) = (Vect α k)
-- ANCHOR_END: moreNames
-- ANCHOR: plusRinfo
example {k} := (Nat.plusR 0 k, k)
example := Nat.add
section
open Nat
example := plusR
example := plusL
end
-- ANCHOR_END: plusRinfo
-- ANCHOR: congr
example := @congrArg
section
variable {x y : α} {f : α → β}
example : x = y → f x = f y := congrArg f
end
example {n k} := Nat.plusR (n + 1) k + 1 = Nat.plusR n (k + 1) + 1
-- ANCHOR_END: congr
-- ANCHOR: exercises
example {n k : Nat} := n.plusR k = n + k
-- ANCHOR_END: exercises
-- ANCHOR: Vect
section
open Vect
example := @cons
example := @nil
end
-- ANCHOR_END: Vect
namespace Eta
axiom α : Type
axiom β : Type
axiom f : α → β
example : f = fun x => f x := Eq.refl f
end Eta |
fp-lean/examples/Examples/DependentTypes/IndicesParameters.lean | import ExampleSupport
import Examples.DependentTypes
-- ANCHOR: WithParameter
inductive WithParameter (α : Type u) : Type u where
| test : α → WithParameter α
-- ANCHOR_END: WithParameter
-- ANCHOR: WithTwoParameters
inductive WithTwoParameters (α : Type u) (β : Type v) : Type (max u v) where
| test : α → β → WithTwoParameters α β
-- ANCHOR_END: WithTwoParameters
-- ANCHOR: WithParameterAfterColon
inductive WithParameterAfterColon : Type u → Type u where
| test : α → WithParameterAfterColon α
-- ANCHOR_END: WithParameterAfterColon
-- ANCHOR: WithParameterAfterColon2
inductive WithParameterAfterColon2 : Type u → Type u where
| test1 : α → WithParameterAfterColon2 α
| test2 : WithParameterAfterColon2 α
-- ANCHOR_END: WithParameterAfterColon2
-- ANCHOR: WithParameterAfterColonDifferentNames
inductive WithParameterAfterColonDifferentNames : Type u → Type u where
| test1 : α → WithParameterAfterColonDifferentNames α
| test2 : β → WithParameterAfterColonDifferentNames β
-- ANCHOR_END: WithParameterAfterColonDifferentNames
/--
error: Mismatched inductive type parameter in
WithParameterBeforeColonDifferentNames β
The provided argument
β
is not definitionally equal to the expected parameter
α
Note: The value of parameter `α` must be fixed throughout the inductive declaration. Consider making this parameter an index if it must vary.
-/
#check_msgs in
-- ANCHOR: WithParameterBeforeColonDifferentNames
inductive WithParameterBeforeColonDifferentNames (α : Type u) : Type u where
| test1 : α → WithParameterBeforeColonDifferentNames α
| test2 : β → WithParameterBeforeColonDifferentNames β
-- ANCHOR_END: WithParameterBeforeColonDifferentNames
/--
error: Mismatched inductive type parameter in
WithNamedIndex (α × α)
The provided argument
α × α
is not definitionally equal to the expected parameter
α
Note: The value of parameter `α` must be fixed throughout the inductive declaration. Consider making this parameter an index if it must vary.
-/
#check_msgs in
-- ANCHOR: WithNamedIndex
inductive WithNamedIndex (α : Type u) : Type (u + 1) where
| test1 : WithNamedIndex α
| test2 : WithNamedIndex α → WithNamedIndex α → WithNamedIndex (α × α)
-- ANCHOR_END: WithNamedIndex
-- ANCHOR: WithIndex
inductive WithIndex : Type u → Type (u + 1) where
| test1 : WithIndex α
| test2 : WithIndex α → WithIndex α → WithIndex (α × α)
-- ANCHOR_END: WithIndex
/--
error: Invalid universe level in constructor `ParamAfterIndex.test1`: Parameter `γ` has type
Type u
at universe level
u+2
which is not less than or equal to the inductive type's resulting universe level
u+1
-/
#check_msgs in
-- ANCHOR: ParamAfterIndex
inductive ParamAfterIndex : Nat → Type u → Type u where
| test1 : ParamAfterIndex 0 γ
| test2 : ParamAfterIndex n γ → ParamAfterIndex k γ → ParamAfterIndex (n + k) γ
-- ANCHOR_END: ParamAfterIndex
/--
error: Mismatched inductive type parameter in
NatParam 4 5
The provided argument
4
is not definitionally equal to the expected parameter
n
Note: The value of parameter `n` must be fixed throughout the inductive declaration. Consider making this parameter an index if it must vary.
-/
#check_msgs in
-- ANCHOR: NatParamFour
inductive NatParam (n : Nat) : Nat → Type u where
| five : NatParam 4 5
-- ANCHOR_END: NatParamFour
-- ANCHOR: NatParam
inductive NatParam (n : Nat) : Nat → Type u where
| five : NatParam n 5
-- ANCHOR_END: NatParam
/-- info:
inductive Vect.{u} : Type u → Nat → Type u
number of parameters: 1
constructors:
Vect.nil : {α : Type u} → Vect α 0
Vect.cons : {α : Type u} → {n : Nat} → α → Vect α n → Vect α (n + 1)
-/
#check_msgs in
-- ANCHOR: printVect
#print Vect
-- ANCHOR_END: printVect |
fp-lean/examples/Examples/Monads/Class.lean | import ExampleSupport
import Examples.Monads
import Examples.Monads.Many
set_option linter.unusedVariables false
-- ANCHOR: Names
example := Option
example := IO
section
variable (ε : Type)
example := Except ε
variable {α : Type}
example := Option α
example := Except String α
example := @Functor.map
end
-- ANCHOR_END: Names
namespace Class
variable {α β : Type} {m : Type → Type}
-- ANCHOR: FakeMonad
class Monad (m : Type → Type) where
pure : α → m α
bind : m α → (α → m β) → m β
-- ANCHOR_END: FakeMonad
end Class
-- ANCHOR: MonadOptionExcept
instance : Monad Option where
pure x := some x
bind opt next :=
match opt with
| none => none
| some x => next x
instance : Monad (Except ε) where
pure x := Except.ok x
bind attempt next :=
match attempt with
| Except.error e => Except.error e
| Except.ok x => next x
-- ANCHOR_END: MonadOptionExcept
section
variable {α : Type} {m : Type → Type}
-- ANCHOR: firstThirdFifthSeventhMonad
def firstThirdFifthSeventh [Monad m] (lookup : List α → Nat → m α)
(xs : List α) : m (α × α × α × α) :=
lookup xs 0 >>= fun first =>
lookup xs 2 >>= fun third =>
lookup xs 4 >>= fun fifth =>
lookup xs 6 >>= fun seventh =>
pure (first, third, fifth, seventh)
-- ANCHOR_END: firstThirdFifthSeventhMonad
end
-- ANCHOR: animals
def slowMammals : List String :=
["Three-toed sloth", "Slow loris"]
def fastBirds : List String := [
"Peregrine falcon",
"Saker falcon",
"Golden eagle",
"Gray-headed albatross",
"Spur-winged goose",
"Swift",
"Anna's hummingbird"
]
-- ANCHOR_END: animals
/-- info:
none
-/
#check_msgs in
-- ANCHOR: noneSlow
#eval firstThirdFifthSeventh (fun xs i => xs[i]?) slowMammals
-- ANCHOR_END: noneSlow
/-- info:
some ("Peregrine falcon", "Golden eagle", "Spur-winged goose", "Anna's hummingbird")
-/
#check_msgs in
-- ANCHOR: someFast
#eval firstThirdFifthSeventh (fun xs i => xs[i]?) fastBirds
-- ANCHOR_END: someFast
namespace Errs
-- ANCHOR: getOrExcept
def getOrExcept (xs : List α) (i : Nat) : Except String α :=
match xs[i]? with
| none =>
Except.error s!"Index {i} not found (maximum is {xs.length - 1})"
| some x =>
Except.ok x
-- ANCHOR_END: getOrExcept
/-- info:
Except.error "Index 2 not found (maximum is 1)"
-/
#check_msgs in
-- ANCHOR: errorSlow
#eval firstThirdFifthSeventh getOrExcept slowMammals
-- ANCHOR_END: errorSlow
/-- info:
Except.ok ("Peregrine falcon", "Golden eagle", "Spur-winged goose", "Anna's hummingbird")
-/
#check_msgs in
-- ANCHOR: okFast
#eval firstThirdFifthSeventh getOrExcept fastBirds
-- ANCHOR_END: okFast
end Errs
namespace IdentMonad
-- ANCHOR: IdMonad
def Id (t : Type) : Type := t
instance : Monad Id where
pure x := x
bind x f := f x
-- ANCHOR_END: IdMonad
end IdentMonad
-- ANCHOR: IdMore
example : Id α = α := rfl
example : (α → Id α) = (α → α) := rfl
example : (α → (α → Id β) → Id β) = (α → (α → β) → β) := rfl
-- ANCHOR_END: IdMore
namespace MyListStuff
variable {α β : Type} {m : Type → Type}
-- ANCHOR: mapM
def mapM [Monad m] (f : α → m β) : List α → m (List β)
| [] => pure []
| x :: xs =>
f x >>= fun hd =>
mapM f xs >>= fun tl =>
pure (hd :: tl)
-- ANCHOR_END: mapM
open Monads.State (State get set)
-- ANCHOR: StateEx
section
variable {σ α : Type}
example := State σ α
example := Type → Type
example : State σ σ := get
example : σ → State σ Unit := set
end
-- ANCHOR_END: StateEx
-- ANCHOR: StateMonad
instance : Monad (State σ) where
pure x := fun s => (s, x)
bind first next :=
fun s =>
let (s', x) := first s
next x s'
-- ANCHOR_END: StateMonad
-- ANCHOR: increment
def increment (howMuch : Int) : State Int Int :=
get >>= fun i =>
set (i + howMuch) >>= fun () =>
pure i
-- ANCHOR_END: increment
-- ANCHOR: mapMincrement
example : List Int → State Int (List Int) := mapM increment
-- ANCHOR_END: mapMincrement
-- ANCHOR: mapMincrement2
example : List Int → Int → (Int × List Int) := mapM increment
-- ANCHOR_END: mapMincrement2
/-- info:
(15, [0, 1, 3, 6, 10])
-/
#check_msgs in
-- ANCHOR: mapMincrementOut
#eval mapM increment [1, 2, 3, 4, 5] 0
-- ANCHOR_END: mapMincrementOut
-- TODO fix error about unknown universe levels here
-- evaluation steps : (State Int (List Int) : Type) {{{ mapMincrOutSteps }}}
-- mapM increment [1, 2]
-- ===>
-- match [1, 2] with
-- | [] => pure []
-- | x :: xs =>
-- increment x >>= fun hd =>
-- mapM increment xs >>= fun tl =>
-- pure (hd :: tl)
-- ===>
-- increment 1 >>= fun hd =>
-- mapM increment [2] >>= fun tl =>
-- pure (hd :: tl)
-- ===>
-- (get >>= fun i =>
-- set (i + 1) >>= fun () =>
-- pure i) >>= fun hd =>
-- mapM increment [2] >>= fun tl =>
-- pure (hd :: tl)
-- end evaluation steps
-- TODO same
-- evaluation steps : (State Int (List Int) : Type) {{{ mapMincrOutSteps }}}
-- mapM increment []
-- ===>
-- match [] with
-- | [] => pure []
-- | x :: xs =>
-- increment x >>= fun hd =>
-- mapM increment xs >>= fun tl =>
-- pure (hd :: tl)
-- ===>
-- pure []
-- ===>
-- fun s => ([], s)
-- end evaluation steps
open Monads.Writer (WithLog save isEven)
-- ANCHOR: MonadWriter
instance : Monad (WithLog logged) where
pure x := {log := [], val := x}
bind result next :=
let {log := thisOut, val := thisRes} := result
let {log := nextOut, val := nextRes} := next thisRes
{log := thisOut ++ nextOut, val := nextRes}
-- ANCHOR_END: MonadWriter
-- ANCHOR: saveIfEven
def saveIfEven (i : Int) : WithLog Int Int :=
(if isEven i then
save i
else pure ()) >>= fun () =>
pure i
-- ANCHOR_END: saveIfEven
/-- info:
{ log := [2, 4], val := [1, 2, 3, 4, 5] }
-/
#check_msgs in
-- ANCHOR: mapMsaveIfEven
#eval mapM saveIfEven [1, 2, 3, 4, 5]
-- ANCHOR_END: mapMsaveIfEven
discarding
#check_msgs in
-- ANCHOR: mapMId
def numbers := mapM (m := Id) (do return · + 1) [1, 2, 3, 4, 5]
-- ANCHOR_END: mapMId
stop discarding
discarding
/--
error: typeclass instance problem is stuck
Pure ?m.6
Note: Lean will not try to resolve this typeclass instance problem because the type argument to `Pure` is a metavariable. This argument must be fully determined before Lean will try to resolve the typeclass.
Hint: Adding type annotations and supplying implicit arguments to functions can give Lean more information for typeclass resolution. For example, if you have a variable `x` that you intend to be a `Nat`, but Lean reports it as having an unresolved type like `?m`, replacing `x` with `(x : Nat)` can get typeclass resolution un-stuck.
-/
#check_msgs in
-- ANCHOR: mapMIdNoHint
def numbers := mapM (do return · + 1) [1, 2, 3, 4, 5]
-- ANCHOR_END: mapMIdNoHint
stop discarding
discarding
/--
error: typeclass instance problem is stuck
Pure ?m.6
Note: Lean will not try to resolve this typeclass instance problem because the type argument to `Pure` is a metavariable. This argument must be fully determined before Lean will try to resolve the typeclass.
Hint: Adding type annotations and supplying implicit arguments to functions can give Lean more information for typeclass resolution. For example, if you have a variable `x` that you intend to be a `Nat`, but Lean reports it as having an unresolved type like `?m`, replacing `x` with `(x : Nat)` can get typeclass resolution un-stuck.
-/
#check_msgs in
-- ANCHOR: mapMIdId
def numbers := mapM (do return · + 1) [1, 2, 3, 4, 5]
-- ANCHOR_END: mapMIdId
stop discarding
end MyListStuff
-- ANCHOR: ExprArith
inductive Expr (op : Type) where
| const : Int → Expr op
| prim : op → Expr op → Expr op → Expr op
inductive Arith where
| plus
| minus
| times
| div
-- ANCHOR_END: ExprArith
-- ANCHOR: twoPlusThree
open Expr in
open Arith in
def twoPlusThree : Expr Arith :=
prim plus (const 2) (const 3)
-- ANCHOR_END: twoPlusThree
-- ANCHOR: exampleArithExpr
open Expr in
open Arith in
def fourteenDivided : Expr Arith :=
prim div (const 14)
(prim minus (const 45)
(prim times (const 5)
(const 9)))
-- ANCHOR_END: exampleArithExpr
namespace One
-- ANCHOR: evaluateOptionCommingled
def evaluateOption : Expr Arith → Option Int
| Expr.const i => pure i
| Expr.prim p e1 e2 =>
evaluateOption e1 >>= fun v1 =>
evaluateOption e2 >>= fun v2 =>
match p with
| Arith.plus => pure (v1 + v2)
| Arith.minus => pure (v1 - v2)
| Arith.times => pure (v1 * v2)
| Arith.div => if v2 == 0 then none else pure (v1 / v2)
-- ANCHOR_END: evaluateOptionCommingled
end One
namespace Two
-- ANCHOR: evaluateOptionSplit
def applyPrim : Arith → Int → Int → Option Int
| Arith.plus, x, y => pure (x + y)
| Arith.minus, x, y => pure (x - y)
| Arith.times, x, y => pure (x * y)
| Arith.div, x, y => if y == 0 then none else pure (x / y)
def evaluateOption : Expr Arith → Option Int
| Expr.const i => pure i
| Expr.prim p e1 e2 =>
evaluateOption e1 >>= fun v1 =>
evaluateOption e2 >>= fun v2 =>
applyPrim p v1 v2
-- ANCHOR_END: evaluateOptionSplit
/-- info:
none
-/
#check_msgs in
-- ANCHOR: fourteenDivOption
#eval evaluateOption fourteenDivided
-- ANCHOR_END: fourteenDivOption
end Two
namespace Three
-- ANCHOR: evaluateExcept
def applyPrim : Arith → Int → Int → Except String Int
| Arith.plus, x, y => pure (x + y)
| Arith.minus, x, y => pure (x - y)
| Arith.times, x, y => pure (x * y)
| Arith.div, x, y =>
if y == 0 then
Except.error s!"Tried to divide {x} by zero"
else pure (x / y)
def evaluateExcept : Expr Arith → Except String Int
| Expr.const i => pure i
| Expr.prim p e1 e2 =>
evaluateExcept e1 >>= fun v1 =>
evaluateExcept e2 >>= fun v2 =>
applyPrim p v1 v2
-- ANCHOR_END: evaluateExcept
end Three
namespace Four
-- ANCHOR: evaluateM
def applyPrimOption : Arith → Int → Int → Option Int
| Arith.plus, x, y => pure (x + y)
| Arith.minus, x, y => pure (x - y)
| Arith.times, x, y => pure (x * y)
| Arith.div, x, y =>
if y == 0 then
none
else pure (x / y)
def applyPrimExcept : Arith → Int → Int → Except String Int
| Arith.plus, x, y => pure (x + y)
| Arith.minus, x, y => pure (x - y)
| Arith.times, x, y => pure (x * y)
| Arith.div, x, y =>
if y == 0 then
Except.error s!"Tried to divide {x} by zero"
else pure (x / y)
def evaluateM [Monad m]
(applyPrim : Arith → Int → Int → m Int) :
Expr Arith → m Int
| Expr.const i => pure i
| Expr.prim p e1 e2 =>
evaluateM applyPrim e1 >>= fun v1 =>
evaluateM applyPrim e2 >>= fun v2 =>
applyPrim p v1 v2
-- ANCHOR_END: evaluateM
/-- info:
none
-/
#check_msgs in
-- ANCHOR: evaluateMOption
#eval evaluateM applyPrimOption fourteenDivided
-- ANCHOR_END: evaluateMOption
/-- info:
Except.error "Tried to divide 14 by zero"
-/
#check_msgs in
-- ANCHOR: evaluateMExcept
#eval evaluateM applyPrimExcept fourteenDivided
-- ANCHOR_END: evaluateMExcept
end Four
namespace FourPointFive
-- ANCHOR: evaluateMRefactored
def applyDivOption (x : Int) (y : Int) : Option Int :=
if y == 0 then
none
else pure (x / y)
def applyDivExcept (x : Int) (y : Int) : Except String Int :=
if y == 0 then
Except.error s!"Tried to divide {x} by zero"
else pure (x / y)
def applyPrim [Monad m]
(applyDiv : Int → Int → m Int) :
Arith → Int → Int → m Int
| Arith.plus, x, y => pure (x + y)
| Arith.minus, x, y => pure (x - y)
| Arith.times, x, y => pure (x * y)
| Arith.div, x, y => applyDiv x y
def evaluateM [Monad m]
(applyDiv : Int → Int → m Int) :
Expr Arith → m Int
| Expr.const i => pure i
| Expr.prim p e1 e2 =>
evaluateM applyDiv e1 >>= fun v1 =>
evaluateM applyDiv e2 >>= fun v2 =>
applyPrim applyDiv p v1 v2
-- ANCHOR_END: evaluateMRefactored
end FourPointFive
example : Four.evaluateM Four.applyPrimOption = FourPointFive.evaluateM FourPointFive.applyDivOption := by
funext e
induction e with
| const => simp [Four.evaluateM, FourPointFive.evaluateM]
| prim p e1 e2 ih1 ih2 =>
simp [Four.evaluateM, FourPointFive.evaluateM, *]
rfl
example : Four.evaluateM Four.applyPrimExcept = FourPointFive.evaluateM FourPointFive.applyDivExcept := by
funext e
induction e with
| const => simp [Four.evaluateM, FourPointFive.evaluateM]
| prim p e1 e2 ih1 ih2 =>
simp [Four.evaluateM, FourPointFive.evaluateM, *]
rfl
-- ANCHOR: PrimCanFail
inductive Prim (special : Type) where
| plus
| minus
| times
| other : special → Prim special
inductive CanFail where
| div
-- ANCHOR_END: PrimCanFail
-- ANCHOR: evaluateMMorePoly
def divOption : CanFail → Int → Int → Option Int
| CanFail.div, x, y => if y == 0 then none else pure (x / y)
def divExcept : CanFail → Int → Int → Except String Int
| CanFail.div, x, y =>
if y == 0 then
Except.error s!"Tried to divide {x} by zero"
else pure (x / y)
def applyPrim [Monad m]
(applySpecial : special → Int → Int → m Int) :
Prim special → Int → Int → m Int
| Prim.plus, x, y => pure (x + y)
| Prim.minus, x, y => pure (x - y)
| Prim.times, x, y => pure (x * y)
| Prim.other op, x, y => applySpecial op x y
def evaluateM [Monad m]
(applySpecial : special → Int → Int → m Int) :
Expr (Prim special) → m Int
| Expr.const i => pure i
| Expr.prim p e1 e2 =>
evaluateM applySpecial e1 >>= fun v1 =>
evaluateM applySpecial e2 >>= fun v2 =>
applyPrim applySpecial p v1 v2
-- ANCHOR_END: evaluateMMorePoly
-- ANCHOR: applyEmpty
def applyEmpty [Monad m] (op : Empty) (_ : Int) (_ : Int) : m Int :=
nomatch op
-- ANCHOR_END: applyEmpty
-- ANCHOR: nomatch
section
variable {E : Empty}
example : α := nomatch E
end
-- ANCHOR_END: nomatch
-- ANCHOR: etc
example := @List.cons
example := @List.lookup
-- ANCHOR_END: etc
/-- info:
-9
-/
#check_msgs in
-- ANCHOR: evalId
open Expr Prim in
#eval evaluateM (m := Id) applyEmpty (prim plus (const 5) (const (-14)))
-- ANCHOR_END: evalId
-- ANCHOR: NeedsSearch
inductive NeedsSearch
| div
| choose
def applySearch : NeedsSearch → Int → Int → Many Int
| NeedsSearch.choose, x, y =>
Many.fromList [x, y]
| NeedsSearch.div, x, y =>
if y == 0 then
Many.none
else Many.one (x / y)
-- ANCHOR_END: NeedsSearch
section
-- ANCHOR: opening
open Expr Prim NeedsSearch
-- ANCHOR_END: opening
/-- info:
[3, 6]
-/
#check_msgs in
-- ANCHOR: searchA
#eval
(evaluateM applySearch
(prim plus (const 1)
(prim (other choose) (const 2)
(const 5)))).takeAll
-- ANCHOR_END: searchA
/-- info:
[]
-/
#check_msgs in
-- ANCHOR: searchB
#eval
(evaluateM applySearch
(prim plus (const 1)
(prim (other div) (const 2)
(const 0)))).takeAll
-- ANCHOR_END: searchB
/-- info:
[9]
-/
#check_msgs in
-- ANCHOR: searchC
#eval
(evaluateM applySearch
(prim (other div) (const 90)
(prim plus (prim (other choose) (const (-5)) (const 5))
(const 5)))).takeAll
-- ANCHOR_END: searchC
end
-- ANCHOR: MonadContract
section
example := [BEq, Hashable]
variable {m} [Monad m] [LawfulMonad m]
variable {v : α} {f : α → m β}
example : bind (pure v) f = f v := by simp
variable {v : m α}
-- ANCHOR: MonadContract2
example : bind v pure = v := by simp
example : bind (bind v f) g = bind v (fun x => bind (f x) g) := by simp
end
-- ANCHOR_END: MonadContract2
-- ANCHOR_END: MonadContract
-- ANCHOR: Reader
def Reader (ρ : Type) (α : Type) : Type := ρ → α
def read : Reader ρ ρ := fun env => env
-- ANCHOR_END: Reader
namespace Temp
discarding
/-- error:
don't know how to synthesize placeholder
context:
ρ α β : Type
result : ρ → α
next : α → ρ → β
⊢ ρ → β
-/
#check_msgs in
-- ANCHOR: readerbind0
def Reader.bind {ρ : Type} {α : Type} {β : Type}
(result : ρ → α) (next : α → ρ → β) : ρ → β :=
_
-- ANCHOR_END: readerbind0
stop discarding
discarding
/-- error:
don't know how to synthesize placeholder
context:
ρ α β : Type
result : ρ → α
next : α → ρ → β
env : ρ
⊢ β
-/
#check_msgs in
-- ANCHOR: readerbind1
def Reader.bind {ρ : Type} {α : Type} {β : Type}
(result : ρ → α) (next : α → ρ → β) : ρ → β :=
fun env => _
-- ANCHOR_END: readerbind1
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
ρ α β : Type
result : ρ → α
next : α → ρ → β
env : ρ
⊢ ρ
---
error: don't know how to synthesize placeholder
context:
ρ α β : Type
result : ρ → α
next : α → ρ → β
env : ρ
⊢ α
-/
#check_msgs in
-- ANCHOR: readerbind2a
def Reader.bind {ρ : Type} {α : Type} {β : Type}
(result : ρ → α) (next : α → ρ → β) : ρ → β :=
fun env => next _ _
-- ANCHOR_END: readerbind2a
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
ρ α β : Type
result : ρ → α
next : α → ρ → β
env : ρ
⊢ ρ
---
error: don't know how to synthesize placeholder
context:
ρ α β : Type
result : ρ → α
next : α → ρ → β
env : ρ
⊢ α
-/
#check_msgs in
-- ANCHOR: readerbind2b
def Reader.bind {ρ : Type} {α : Type} {β : Type}
(result : ρ → α) (next : α → ρ → β) : ρ → β :=
fun env => next _ _
-- ANCHOR_END: readerbind2b
stop discarding
discarding
/--
error: don't know how to synthesize placeholder
context:
ρ α β : Type
result : ρ → α
next : α → ρ → β
env : ρ
⊢ ρ
---
error: don't know how to synthesize placeholder
context:
ρ α β : Type
result : ρ → α
next : α → ρ → β
env : ρ
⊢ ρ
-/
#check_msgs in
-- ANCHOR: readerbind3
def Reader.bind {ρ : Type} {α : Type} {β : Type}
(result : ρ → α) (next : α → ρ → β) : ρ → β :=
fun env => next (result _) _
-- ANCHOR_END: readerbind3
stop discarding
-- ANCHOR: readerbind4
def Reader.bind {ρ : Type} {α : Type} {β : Type}
(result : ρ → α) (next : α → ρ → β) : ρ → β :=
fun env => next (result env) env
-- ANCHOR_END: readerbind4
end Temp
-- ANCHOR: Readerbind
def Reader.bind
(result : Reader ρ α)
(next : α → Reader ρ β) : Reader ρ β :=
fun env => next (result env) env
-- ANCHOR_END: Readerbind
namespace TTT
variable (α : Type)
variable (β : Type)
variable (ρ : Type)
-- ANCHOR: readerBindType
example : Reader ρ α → (α → Reader ρ β) → Reader ρ β := Reader.bind
-- ANCHOR_END: readerBindType
-- ANCHOR: readerBindTypeEval
example : (Reader ρ α → (α → Reader ρ β) → Reader ρ β) = ((ρ → α) → (α → ρ → β) → (ρ → β)) := by rfl
-- ANCHOR_END: readerBindTypeEval
end TTT
-- ANCHOR: ReaderPure
def Reader.pure (x : α) : Reader ρ α := fun _ => x
-- ANCHOR_END: ReaderPure
-- ANCHOR: eta
section
variable (f : α → β)
example : (fun x => f x) = f := rfl
end
-- ANCHOR_END: eta
namespace MonadLaws
variable (α : Type)
variable (ρ : Type)
variable (β : Type)
variable (γ : Type)
variable (v : α)
variable (r : Reader ρ α)
variable (f : α → Reader ρ β)
variable (g : β → Reader ρ γ)
evaluation steps {{{ ReaderMonad1 }}}
-- ANCHOR: ReaderMonad1
Reader.bind (Reader.pure v) f
===>
fun env => f ((Reader.pure v) env) env
===>
fun env => f ((fun _ => v) env) env
===>
fun env => f v env
===>
f v
-- ANCHOR_END: ReaderMonad1
end evaluation steps
evaluation steps {{{ ReaderMonad2 }}}
-- ANCHOR: ReaderMonad2
Reader.bind r Reader.pure
===>
fun env => Reader.pure (r env) env
===>
fun env => (fun _ => (r env)) env
===>
fun env => r env
-- ANCHOR_END: ReaderMonad2
end evaluation steps
evaluation steps {{{ ReaderMonad3a }}}
-- ANCHOR: ReaderMonad3a
Reader.bind (Reader.bind r f) g
===>
fun env => g ((Reader.bind r f) env) env
===>
fun env => g ((fun env' => f (r env') env') env) env
===>
fun env => g (f (r env) env) env
-- ANCHOR_END: ReaderMonad3a
end evaluation steps
evaluation steps {{{ ReaderMonad3b }}}
-- ANCHOR: ReaderMonad3b
Reader.bind r (fun x => Reader.bind (f x) g)
===>
Reader.bind r (fun x => fun env => g (f x env) env)
===>
fun env => (fun x => fun env' => g (f x env') env') (r env) env
===>
fun env => (fun env' => g (f (r env) env') env') env
===>
fun env => g (f (r env) env) env
-- ANCHOR_END: ReaderMonad3b
end evaluation steps
end MonadLaws
-- ANCHOR: MonadReaderInst
instance : Monad (Reader ρ) where
pure x := fun _ => x
bind x f := fun env => f (x env) env
-- ANCHOR_END: MonadReaderInst
instance : LawfulMonad (Reader ρ) where
map_const := by
simp [Functor.mapConst, Function.comp, Functor.map]
id_map x := by
simp [Functor.map]
seqLeft_eq x _ := by
simp [SeqLeft.seqLeft, Seq.seq, Functor.map]
seqRight_eq _ y := by
simp [SeqRight.seqRight, Seq.seq, Functor.map]
pure_seq g x := by
simp [Seq.seq, Functor.map, pure]
bind_pure_comp f x := by
simp [Functor.map, bind, pure]
bind_map f x := by
simp [Seq.seq, bind, Functor.map]
pure_bind x f := by
simp [pure, bind]
bind_assoc x f g := by
simp [bind]
-- ANCHOR: Env
abbrev Env : Type := List (String × (Int → Int → Int))
-- ANCHOR_END: Env
-- ANCHOR: applyPrimReader
def applyPrimReader (op : String) (x : Int) (y : Int) : Reader Env Int :=
read >>= fun env =>
match env.lookup op with
| none => pure 0
| some f => pure (f x y)
-- ANCHOR_END: applyPrimReader
-- ANCHOR: exampleEnv
def exampleEnv : Env := [("max", max), ("mod", (· % ·))]
-- ANCHOR_END: exampleEnv
/-- info:
9
-/
#check_msgs in
-- ANCHOR: readerEval
open Expr Prim in
#eval
evaluateM applyPrimReader
(prim (other "max") (prim plus (const 5) (const 4))
(prim times (const 3)
(const 2)))
exampleEnv
-- ANCHOR_END: readerEval
namespace Exercises
---ANCHOR: ex1
def BinTree.mapM [Monad m] (f : α → m β) : BinTree α → m (BinTree β)
| .leaf => pure .leaf
| .branch l x r =>
mapM f l >>= fun l' =>
f x >>= fun x' =>
mapM f r >>= fun r' =>
pure (BinTree.branch l' x' r')
---ANCHOR_END: ex1
namespace Busted
set_option linter.unusedVariables false in
-- ANCHOR: badOptionMonad
instance : Monad Option where
pure x := some x
bind opt next := none
-- ANCHOR_END: badOptionMonad
end Busted
open Monads.Writer (WithLog save)
instance : Monad (WithLog logged) where
pure x := {log := [], val := x}
bind result next :=
let {log := thisOut, val := thisRes} := result
let {log := nextOut, val := nextRes} := next thisRes
{log := thisOut ++ nextOut, val := nextRes}
-- ANCHOR: ReprInstances
deriving instance Repr for WithLog
deriving instance Repr for Empty
deriving instance Repr for Prim
-- ANCHOR_END: ReprInstances
-- ANCHOR: ToTrace
inductive ToTrace (α : Type) : Type where
| trace : α → ToTrace α
-- ANCHOR_END: ToTrace
def applyTraced : ToTrace (Prim Empty) → Int → Int → WithLog (Prim Empty × Int × Int) Int
| ToTrace.trace op, x, y =>
save (op, x, y) >>= fun () =>
applyPrim applyEmpty op x y
-- ANCHOR: applyTracedType
example : ToTrace (Prim Empty) → Int → Int → WithLog (Prim Empty × Int × Int) Int := applyTraced
-- ANCHOR_END: applyTracedType
--ANCHOR: ToTraceExpr
example := Expr (Prim (ToTrace (Prim Empty)))
--ANCHOR_END: ToTraceExpr
/-- info:
{ log := [(Prim.plus, 1, 2), (Prim.minus, 3, 4), (Prim.times, 3, -1)], val := -3 }
-/
#check_msgs in
-- ANCHOR: evalTraced
open Expr Prim ToTrace in
#eval
evaluateM applyTraced
(prim (other (trace times))
(prim (other (trace plus)) (const 1)
(const 2))
(prim (other (trace minus)) (const 3)
(const 4)))
-- ANCHOR_END: evalTraced
-- ANCHOR: ReaderFail
def ReaderOption (ρ : Type) (α : Type) : Type := ρ → Option α
def ReaderExcept (ε : Type) (ρ : Type) (α : Type) : Type := ρ → Except ε α
-- ANCHOR_END: ReaderFail
end Exercises
-- def evalOpWithLog (op : Prim Empty) (x : Int) (y : Int) : WithLog (Prim Empty × Int × Int) Int :=
-- save (op, x, y) >>= fun () =>
-- match op with
-- | Prim.plus => pure (x + y)
-- | Prim.minus => pure (x - y)
-- | Prim.times => pure (x * y)
--
-- def evalOpId (op : Prim Empty) (x : Int) (y : Int) : Id Int :=
-- match op with
-- | Prim.plus => pure (x + y)
-- | Prim.minus => pure (x - y)
-- | Prim.times => pure (x * y)
-- open Monads.State (State get set)
-- def evalOpState (op : Prim Empty) (x : Int) (y : Int) : State Nat Int :=
-- get >>= fun i =>
-- set (i + 1) >>= fun () =>
-- match op with
-- | Prim.plus => pure (x + y)
-- | Prim.minus => pure (x - y)
-- | Prim.times => pure (x * y)
-- deriving instance Repr for Prim
-- #eval evaluate evalOpOption (Expr.prim Prim.plus (Expr.const 2) (Expr.prim (Prim.other CanFail.div) (Expr.const 3) (Expr.const 5)))
-- #eval evaluate evalOpOption (Expr.prim Prim.plus (Expr.const 2) (Expr.prim (Prim.other CanFail.div) (Expr.const 3) (Expr.const 0)))
-- #eval evaluate evalOpExcept (Expr.prim Prim.plus (Expr.const 2) (Expr.prim (Prim.other CanFail.div) (Expr.const 3) (Expr.const 5)))
-- #eval evaluate evalOpExcept (Expr.prim Prim.plus (Expr.const 2) (Expr.prim (Prim.other CanFail.div) (Expr.const 3) (Expr.const 0)))
-- #eval evaluate evalOpWithLog (Expr.prim Prim.plus (Expr.const 2) (Expr.prim Prim.times (Expr.const 3) (Expr.const 5)))
-- #eval evaluate evalOpId (Expr.prim Prim.plus (Expr.const 2) (Expr.prim Prim.times (Expr.const 3) (Expr.const 5))) |
fp-lean/examples/Examples/Monads/IO.lean | import ExampleSupport
-- ANCHOR: names
example := IO
section
local instance : Monad IO where
pure := pure
bind := bind
universe u
example {ε} {α}:= EIO ε α
-- ANCHOR: EStateMNames
example {ε} {α} {σ} := EST ε σ α → EST.Out ε σ α
-- ANCHOR_END: EStateMNames
example := @EST.Out.ok
example := @EST.Out.error
example {α}:= BaseIO α
example {ε} := Except ε
example := Type u
end
-- ANCHOR_END: names
/-- info:
inductive Nat : Type
number of parameters: 0
constructors:
Nat.zero : Nat
Nat.succ : Nat → Nat
-/
#check_msgs in
-- ANCHOR: printNat
#print Nat
-- ANCHOR_END: printNat
/-- info:
def Char.isAlpha : Char → Bool :=
fun c => c.isUpper || c.isLower
-/
#check_msgs in
-- ANCHOR: printCharIsAlpha
#print Char.isAlpha
-- ANCHOR_END: printCharIsAlpha
/-- info:
def List.isEmpty.{u} : {α : Type u} → List α → Bool :=
fun {α} x =>
match x with
| [] => true
| head :: tail => false
-/
#check_msgs in
-- ANCHOR: printListIsEmpty
#print List.isEmpty
-- ANCHOR_END: printListIsEmpty
/-- info:
@[reducible] def IO : Type → Type :=
EIO IO.Error
-/
#check_msgs in
-- ANCHOR: printIO
#print IO
-- ANCHOR_END: printIO
/-- info:
inductive IO.Error : Type
number of parameters: 0
constructors:
IO.Error.alreadyExists : Option String → UInt32 → String → IO.Error
IO.Error.otherError : UInt32 → String → IO.Error
IO.Error.resourceBusy : UInt32 → String → IO.Error
IO.Error.resourceVanished : UInt32 → String → IO.Error
IO.Error.unsupportedOperation : UInt32 → String → IO.Error
IO.Error.hardwareFault : UInt32 → String → IO.Error
IO.Error.unsatisfiedConstraints : UInt32 → String → IO.Error
IO.Error.illegalOperation : UInt32 → String → IO.Error
IO.Error.protocolError : UInt32 → String → IO.Error
IO.Error.timeExpired : UInt32 → String → IO.Error
IO.Error.interrupted : String → UInt32 → String → IO.Error
IO.Error.noFileOrDirectory : String → UInt32 → String → IO.Error
IO.Error.invalidArgument : Option String → UInt32 → String → IO.Error
IO.Error.permissionDenied : Option String → UInt32 → String → IO.Error
IO.Error.resourceExhausted : Option String → UInt32 → String → IO.Error
IO.Error.inappropriateType : Option String → UInt32 → String → IO.Error
IO.Error.noSuchThing : Option String → UInt32 → String → IO.Error
IO.Error.unexpectedEof : IO.Error
IO.Error.userError : String → IO.Error
-/
#check_msgs in
-- ANCHOR: printIOError
#print IO.Error
-- ANCHOR_END: printIOError
/-- info:
def EIO : Type → Type → Type :=
fun ε α => EST ε IO.RealWorld α
-/
#check_msgs in
-- ANCHOR: printEIO
#print EIO
-- ANCHOR_END: printEIO
-- ANCHOR: VoidSigma
example {σ} := Void σ
-- ANCHOR_END: VoidSigma
-- ANCHOR: RealWorld
example := IO.RealWorld
-- ANCHOR_END: RealWorld
/-- info:
def EST : Type → Type → Type → Type :=
fun ε σ α => Void σ → EST.Out ε σ α
-/
#check_msgs in
-- ANCHOR: printEStateM
#print EST
-- ANCHOR_END: printEStateM
/-- info:
inductive EST.Out : Type → Type → Type → Type
number of parameters: 3
constructors:
EST.Out.ok : {ε σ α : Type} → α → Void σ → EST.Out ε σ α
EST.Out.error : {ε σ α : Type} → ε → Void σ → EST.Out ε σ α
-/
#check_msgs in
-- ANCHOR: printEStateMResult
#print EST.Out
-- ANCHOR_END: printEStateMResult
/-- info:
protected def EST.pure : {α ε σ : Type} → α → EST ε σ α :=
fun {α ε σ} a s => EST.Out.ok a s
-/
#check_msgs in
-- ANCHOR: printEStateMpure
#print EST.pure
-- ANCHOR_END: printEStateMpure
/-- info:
protected def EST.bind : {ε σ α β : Type} → EST ε σ α → (α → EST ε σ β) → EST ε σ β :=
fun {ε σ α β} x f s =>
match x s with
| EST.Out.ok a s => f a s
| EST.Out.error e s => EST.Out.error e s
-/
#check_msgs in
-- ANCHOR: printEStateMbind
#print EST.bind
-- ANCHOR_END: printEStateMbind |
fp-lean/examples/Examples/Monads/Conveniences.lean | import ExampleSupport
import Examples.Classes
set_option linter.unusedVariables false
-- ANCHOR: SumNames
example := Sum
example := @Sum.inl
example := @Sum.inr
section
open Sum
example := @inl
example := @inr
end
-- ANCHOR_END: SumNames
namespace Old
variable {α : Type}
-- ANCHOR: equalHuhOld
def equal? [BEq α] (x : α) (y : α) : Option α :=
if x == y then
some x
else
none
-- ANCHOR_END: equalHuhOld
end Old
namespace New
variable {α : Type}
-- ANCHOR: equalHuhNew
def equal? [BEq α] (x y : α) : Option α :=
if x == y then
some x
else
none
-- ANCHOR_END: equalHuhNew
end New
example [BEq α] : Old.equal? (α := α) = New.equal? := by rfl
namespace Old
-- ANCHOR: mirrorOld
def BinTree.mirror : BinTree α → BinTree α
| BinTree.leaf => BinTree.leaf
| BinTree.branch l x r => BinTree.branch (mirror r) x (mirror l)
-- ANCHOR_END: mirrorOld
end Old
-- ANCHOR: mirrorNew
def BinTree.mirror : BinTree α → BinTree α
| .leaf => .leaf
| .branch l x r => .branch (mirror r) x (mirror l)
-- ANCHOR_END: mirrorNew
-- ANCHOR: BinTreeEmpty
def BinTree.empty : BinTree α := .leaf
-- ANCHOR_END: BinTreeEmpty
/-- info:
BinTree.empty : BinTree Nat
-/
#check_msgs in
-- ANCHOR: emptyDot
#check (.empty : BinTree Nat)
-- ANCHOR_END: emptyDot
-- ANCHOR: Weekday
inductive Weekday where
| monday
| tuesday
| wednesday
| thursday
| friday
| saturday
| sunday
deriving Repr
-- ANCHOR_END: Weekday
namespace A
-- ANCHOR: isWeekendA
def Weekday.isWeekend (day : Weekday) : Bool :=
match day with
| Weekday.saturday => true
| Weekday.sunday => true
| _ => false
-- ANCHOR_END: isWeekendA
end A
namespace B
-- ANCHOR: isWeekendB
def Weekday.isWeekend (day : Weekday) : Bool :=
match day with
| .saturday => true
| .sunday => true
| _ => false
-- ANCHOR_END: isWeekendB
end B
namespace C
-- ANCHOR: isWeekendC
def Weekday.isWeekend (day : Weekday) : Bool :=
match day with
| .saturday | .sunday => true
| _ => false
-- ANCHOR_END: isWeekendC
end C
namespace D
variable {α : Type}
-- ANCHOR: isWeekendD
def Weekday.isWeekend : Weekday → Bool
| .saturday | .sunday => true
| _ => false
-- ANCHOR_END: isWeekendD
end D
variable {α : Type}
-- ANCHOR: condense
def condense : α ⊕ α → α
| .inl x | .inr x => x
-- ANCHOR_END: condense
-- ANCHOR: stringy
def stringy : Nat ⊕ Weekday → String
| .inl x | .inr x => s!"It is {repr x}"
-- ANCHOR_END: stringy
#eval stringy (.inl 5)
#eval stringy (.inr .monday)
-- ANCHOR: getTheNat
def getTheNat : (Nat × α) ⊕ (Nat × β) → Nat
| .inl (n, x) | .inr (n, y) => n
-- ANCHOR_END: getTheNat
/-- error: Unknown identifier `x` -/
#check_msgs in
-- ANCHOR: getTheAlpha
def getTheAlpha : (Nat × α) ⊕ (Nat × α) → α
| .inl (n, x) | .inr (n, y) => x
-- ANCHOR_END: getTheAlpha
-- ANCHOR: getTheString
def str := "Some string"
def getTheString : (Nat × String) ⊕ (Nat × β) → String
| .inl (n, str) | .inr (n, y) => str
-- ANCHOR_END: getTheString
/-- info:
"twenty"
-/
#check_msgs in
-- ANCHOR: getOne
#eval getTheString (.inl (20, "twenty") : (Nat × String) ⊕ (Nat × String))
-- ANCHOR_END: getOne
/-- info:
"Some string"
-/
#check_msgs in
-- ANCHOR: getTwo
#eval getTheString (.inr (20, "twenty"))
-- ANCHOR_END: getTwo |
fp-lean/examples/Examples/Monads/Many.lean | import ExampleSupport
-- ANCHOR: Many
inductive Many (α : Type) where
| none : Many α
| more : α → (Unit → Many α) → Many α
-- ANCHOR_END: Many
-- ANCHOR: one
def Many.one (x : α) : Many α := Many.more x (fun () => Many.none)
-- ANCHOR_END: one
-- ANCHOR: union
def Many.union : Many α → Many α → Many α
| Many.none, ys => ys
| Many.more x xs, ys => Many.more x (fun () => union (xs ()) ys)
-- ANCHOR_END: union
-- ANCHOR: fromList
def Many.fromList : List α → Many α
| [] => Many.none
| x :: xs => Many.more x (fun () => fromList xs)
-- ANCHOR_END: fromList
-- ANCHOR: take
def Many.take : Nat → Many α → List α
| 0, _ => []
| _ + 1, Many.none => []
| n + 1, Many.more x xs => x :: (xs ()).take n
def Many.takeAll : Many α → List α
| Many.none => []
| Many.more x xs => x :: (xs ()).takeAll
-- ANCHOR_END: take
-- ANCHOR: bind
def Many.bind : Many α → (α → Many β) → Many β
| Many.none, _ =>
Many.none
| Many.more x xs, f =>
(f x).union (bind (xs ()) f)
-- ANCHOR_END: bind
namespace Agh
axiom v : Nat
axiom f : Nat → Many String
evaluation steps {{{ bindLeft }}}
-- ANCHOR: bindLeft
Many.bind (Many.one v) f
===>
Many.bind (Many.more v (fun () => Many.none)) f
===>
(f v).union (Many.bind Many.none f)
===>
(f v).union Many.none
-- ANCHOR_END: bindLeft
end evaluation steps
end Agh
section
local syntax "…" : term
variable {α β γ : Type}
variable {f : α → Many β} {v : Many α}
variable {v₁ : α} {v₂ : α} {v₃ : α} {vₙ : α} {«…» : α}
macro_rules
| `(term|…) => `(«…»)
local instance : Union (Many α) where
union := .union
local instance : Insert α (Many α) where
insert x xs := .more x (fun () => xs)
local instance : Singleton α (Many α) where
singleton x := .one x
-- ANCHOR: vSet
example : Many α := {v₁, v₂, v₃, …, vₙ}
-- ANCHOR_END: vSet
variable {«…» : Many α}
macro_rules
| `(term|…) => `(«…»)
-- ANCHOR: bindOne
example : Many.bind v Many.one = v := by
induction v
. simp [Many.bind, Many.one]
. simp [Many.bind, Many.one, *, Many.union]
-- ANCHOR_END: bindOne
-- ANCHOR: bindAssoc
example {g : β → Many γ} := Many.bind (Many.bind v f) g = Many.bind v (fun x => Many.bind (f x) g)
-- ANCHOR_END: bindAssoc
-- ANCHOR: vSets
example : Many α := {v₁} ∪ {v₂} ∪ {v₃} ∪ … ∪ {vₙ}
-- ANCHOR_END: vSets
variable {«…» : Many β}
macro_rules
| `(term|…) => `(«…»)
evaluation steps -check {{{ bindUnion }}}
-- ANCHOR: bindUnion
Many.bind v f
===>
f v₁ ∪ f v₂ ∪ f v₃ ∪ … ∪ f vₙ
-- ANCHOR_END: bindUnion
end evaluation steps
variable {g : β → Many γ} {«…» : Many γ}
macro_rules
| `(term|…) => `(«…»)
evaluation steps -check {{{ bindBindLeft }}}
--- ANCHOR: bindBindLeft
Many.bind (Many.bind v f) g
===>
Many.bind (f v₁) g ∪
Many.bind (f v₂) g ∪
Many.bind (f v₃) g ∪
… ∪
Many.bind (f vₙ) g
--- ANCHOR_END: bindBindLeft
end evaluation steps
evaluation steps -check {{{ bindBindRight }}}
-- ANCHOR: bindBindRight
Many.bind v (fun x => Many.bind (f x) g)
===>
(fun x => Many.bind (f x) g) v₁ ∪
(fun x => Many.bind (f x) g) v₂ ∪
(fun x => Many.bind (f x) g) v₃ ∪
… ∪
(fun x => Many.bind (f x) g) vₙ
===>
Many.bind (f v₁) g ∪
Many.bind (f v₂) g ∪
Many.bind (f v₃) g ∪
… ∪
Many.bind (f vₙ) g
-- ANCHOR_END: bindBindRight
end evaluation steps
end
-- ANCHOR: MonadMany
instance : Monad Many where
pure := Many.one
bind := Many.bind
-- ANCHOR_END: MonadMany
instance : Alternative Many where
failure := .none
orElse xs ys := Many.union xs (ys ())
def Many.range (n k : Nat) : Many Nat :=
if n < k then Many.more n (fun _ => range (n + 1) k) else Many.none
@[simp]
theorem Many.union_none_right_id : Many.union xs Many.none = xs := by
induction xs <;> simp [union]
case more x xs ih =>
funext _
apply ih
theorem Many.union_assoc : Many.union xs (Many.union ys zs) = Many.union (Many.union xs ys) zs := by
induction xs <;> simp [union]
case more x xs ih =>
funext _
apply ih
@[simp]
theorem Many_bind_pure (ys : Many α) : ys >>= pure = ys := by
induction ys with
| none => simp [bind, Many.bind]
| more y ys ih =>
specialize ih ()
simp [bind, Many.bind, pure, Many.union] at ih
simp [bind, Many.bind, pure, Many.union, ih, Many.one]
@[simp]
theorem Many_bind_one (ys : Many α) : ys.bind Many.one = ys := by
induction ys with
| none => simp [bind, Many.bind]
| more y ys ih =>
specialize ih ()
simp only at ih
simp [bind, Many.bind, pure, Many.union, ih, Many.one]
@[simp]
theorem Many_one_bind : (Many.one x).bind f = f x := by
simp [Many.one, Many.bind]
@[simp]
theorem Many_none_bind : Many.none.bind f = Many.none := by
rfl
instance : LawfulMonad Many where
map_const := by
simp [Functor.map, Functor.mapConst]
id_map xs := by
induction xs <;> simp [Functor.map, Many.bind, Function.comp, Many.union]
case more x xs ih =>
specialize ih ()
simp [Functor.map] at ih
simp [ih, Many.one, Many.union]
seqLeft_eq xs ys := by
induction xs <;> simp [SeqLeft.seqLeft, Seq.seq, Many.bind, Function.const, Functor.map, Many.union, Function.comp]
case more x xs ih =>
specialize ih ()
simp only [SeqLeft.seqLeft, Seq.seq, Functor.map] at ih
simp only [ih]
apply congrArg
simp [Many.union, Many_bind_pure, *]
seqRight_eq xs ys := by
induction xs with
| none =>
simp [SeqRight.seqRight, Many.bind, Seq.seq, Functor.map]
| more x xs ih =>
simp [SeqRight.seqRight, Many.bind]
simp [SeqRight.seqRight, Many.bind] at ih
rw [ih]
simp [Seq.seq, Function.const, Functor.map, Many.bind, Function.comp, Many.one, Many.union]
pure_seq g xs := by
simp [Functor.map, Seq.seq, pure]
bind_pure_comp f xs := by
rfl
bind_map f xs := by
simp [bind, Many.bind, pure, Functor.map, Function.comp, Seq.seq]
pure_bind x f := by
simp [bind, Many.bind, pure, Functor.map, Function.comp, Seq.seq]
bind_assoc xs f g := by
induction xs
case none => simp [bind, Many.bind, Many.union]
case more x xs ih =>
specialize ih ()
simp only [bind] at ih
simp only [bind, Many.bind]
generalize f x = fx
induction fx with
| none =>
simp [Many.union, *]
| more y ys ih2 =>
simp only [Many.union, Many.bind, ih2]
generalize g y = gy
cases gy with simp [Many.union]
| more z zs =>
rw [Many.union_assoc]
-- ANCHOR: addsTo
def addsTo (goal : Nat) : List Nat → Many (List Nat)
| [] =>
if goal == 0 then
pure []
else
Many.none
| x :: xs =>
if x > goal then
addsTo goal xs
else
(addsTo goal xs).union
(addsTo (goal - x) xs >>= fun answer =>
pure (x :: answer))
-- ANCHOR_END: addsTo
-- ANCHOR: printList
def printList [ToString α] : List α → IO Unit
| [] => pure ()
| x :: xs => do
IO.println x
printList xs
-- ANCHOR_END: printList
/-- info:
[7, 8]
[6, 9]
[5, 10]
[4, 5, 6]
[3, 5, 7]
[3, 4, 8]
[2, 6, 7]
[2, 5, 8]
[2, 4, 9]
[2, 3, 10]
[2, 3, 4, 6]
[1, 6, 8]
[1, 5, 9]
[1, 4, 10]
[1, 3, 5, 6]
[1, 3, 4, 7]
[1, 2, 5, 7]
[1, 2, 4, 8]
[1, 2, 3, 9]
[1, 2, 3, 4, 5]
-/
#check_msgs in
-- ANCHOR: addsToFifteen
#eval printList (addsTo 15 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).takeAll
-- ANCHOR_END: addsToFifteen |
fp-lean/examples/Examples/Monads/Do.lean | import ExampleSupport
import Examples.Monads
import Examples.Monads.Class
set_option linter.unusedVariables false
-- ANCHOR: names
example := @HAdd.hAdd
example := IO
example := Unit
section
open List
example := @map
end
-- ANCHOR_END: names
section
variable {m : Type → Type} [Monad m] {E : m α} {E₁ : m β} {E₂ : m γ}
variable {Es : m Unit} {Stmt Stmt₁ : m Unit} {Eₙ : m ζ}
local syntax "…" : term
macro_rules
| `(…) => `(Es)
example :
(
-- ANCHOR: doSugar1a
do E
-- ANCHOR_END: doSugar1a
)
=
-- ANCHOR: doSugar1b
E
-- ANCHOR_END: doSugar1b
:= rfl
example :
(
-- ANCHOR: doSugar2a
do let x ← E₁
Stmt
…
Eₙ
-- ANCHOR_END: doSugar2a
) =
(
-- ANCHOR: doSugar2b
E₁ >>= fun x =>
do Stmt
…
Eₙ
-- ANCHOR_END: doSugar2b
)
:= rfl
example :
(
-- ANCHOR: doSugar4a
do let x := E₁
Stmt
…
Eₙ
-- ANCHOR_END: doSugar4a
) =
(
-- ANCHOR: doSugar4b
let x := E₁
do Stmt
…
Eₙ
-- ANCHOR_END: doSugar4b
)
:= rfl
variable {E₁ : m Unit}
example :
(
-- ANCHOR: doSugar3a
do E₁
Stmt
…
Eₙ
-- ANCHOR_END: doSugar3a
) =
(
-- ANCHOR: doSugar3b
E₁ >>= fun () =>
do Stmt
…
Eₙ
-- ANCHOR_END: doSugar3b
)
:= rfl
end
namespace WithDo
variable {α β : Type} {m : Type → Type}
-- ANCHOR: firstThirdFifthSeventhDo
def firstThirdFifthSeventh [Monad m] (lookup : List α → Nat → m α)
(xs : List α) : m (α × α × α × α) := do
let first ← lookup xs 0
let third ← lookup xs 2
let fifth ← lookup xs 4
let seventh ← lookup xs 6
pure (first, third, fifth, seventh)
-- ANCHOR_END: firstThirdFifthSeventhDo
-- ANCHOR: mapM
def mapM [Monad m] (f : α → m β) : List α → m (List β)
| [] => pure []
| x :: xs => do
let hd ← f x
let tl ← mapM f xs
pure (hd :: tl)
-- ANCHOR_END: mapM
end WithDo
section
variable {α β : Type} {m : Type → Type}
-- ANCHOR: mapMNested
def mapM [Monad m] (f : α → m β) : List α → m (List β)
| [] => pure []
| x :: xs => do
pure ((← f x) :: (← mapM f xs))
-- ANCHOR_END: mapMNested
end
namespace Numbering
open Monads.State
instance : Monad (State σ) where
pure x := fun s => (s, x)
bind first next :=
fun s =>
let (s', x) := first s
next x s'
-- ANCHOR: numberDo
def number (t : BinTree α) : BinTree (Nat × α) :=
let rec helper : BinTree α → State Nat (BinTree (Nat × α))
| BinTree.leaf => pure BinTree.leaf
| BinTree.branch left x right => do
let numberedLeft ← helper left
let n ← get
set (n + 1)
let numberedRight ← helper right
ok (BinTree.branch numberedLeft (n, x) numberedRight)
(helper t 0).snd
-- ANCHOR_END: numberDo
namespace Short
-- ANCHOR: numberDoShort
def increment : State Nat Nat := do
let n ← get
set (n + 1)
pure n
def number (t : BinTree α) : BinTree (Nat × α) :=
let rec helper : BinTree α → State Nat (BinTree (Nat × α))
| BinTree.leaf => pure BinTree.leaf
| BinTree.branch left x right => do
pure
(BinTree.branch
(← helper left)
((← increment), x)
(← helper right))
(helper t 0).snd
-- ANCHOR_END: numberDoShort
end Short
end Numbering |
fp-lean/examples/Examples/ProgramsProofs/Div.lean | import ExampleSupport
discarding
/--
error: fail to show termination for
div
with errors
failed to infer structural recursion:
Not considering parameter k of div:
it is unchanged in the recursive calls
Cannot use parameter k:
failed to eliminate recursive application
div (n - k) k
failed to prove termination, possible solutions:
- Use `have`-expressions to prove the remaining goals
- Use `termination_by` to specify a different well-founded relation
- Use `decreasing_by` to specify your own tactic for discharging this kind of goal
k n : Nat
h✝ : ¬n < k
⊢ n - k < n
-/
#check_msgs in
-- ANCHOR: divTermination
def div (n k : Nat) : Nat :=
if n < k then
0
else
1 + div (n - k) k
-- ANCHOR_END: divTermination
stop discarding
discarding
-- ANCHOR: divRecursiveNeedsProof
def div (n k : Nat) (ok : k ≠ 0) : Nat :=
if h : n < k then
0
else
1 + div (n - k) k ok
-- ANCHOR_END: divRecursiveNeedsProof
stop discarding
-- ANCHOR: divRecursiveWithProof
def div (n k : Nat) (ok : k ≠ 0) : Nat :=
if h : n < k then
0
else
1 + div (n - k) k ok
termination_by n
-- ANCHOR_END: divRecursiveWithProof
-- ANCHOR: NatSubLt
example : ∀ {n k : Nat}, 0 < n → 0 < k → n - k < n := @Nat.sub_lt
-- ANCHOR_END: NatSubLt
#eval div 13 2 (by simp) |
fp-lean/examples/Examples/ProgramsProofs/Fin.lean | import ExampleSupport
namespace FinDef
-- ANCHOR: Fin
structure Fin (n : Nat) where
val : Nat
isLt : LT.lt val n
-- ANCHOR_END: Fin
end FinDef
--ANCHOR: sundries
example := GetElem
example := Array
example := Nat
example {n} := Fin n
example : List (Fin 3) := [0, 1, 2]
example := Fin 0
example := @Subtype
section
variable {n k : Nat}
#synth ToString (Fin n)
#synth OfNat (Fin (n + 1)) k
end
--ANCHOR_END: sundries
/-- info:
5
-/
#check_msgs in
-- ANCHOR: fiveFinEight
#eval (5 : Fin 8)
-- ANCHOR_END: fiveFinEight
/-- info:
5
-/
#check_msgs in
-- ANCHOR: finOverflow
#eval (45 : Fin 10)
-- ANCHOR_END: finOverflow
-- ANCHOR: exercise
def Fin.next? (i : Fin n) : Option (Fin n) :=
if h : i.val + 1 < n then
some ⟨i.val + 1, h⟩
else
none
section
variable {n}
#check (Fin.next? : Fin n → Option (Fin n))
end
-- ANCHOR_END: exercise
/-- info:
some 4
-/
#check_msgs in
-- ANCHOR: nextThreeFin
#eval (3 : Fin 8).next?
-- ANCHOR_END: nextThreeFin
/-- info:
none
-/
#check_msgs in
-- ANCHOR: nextSevenFin
#eval (7 : Fin 8).next?
-- ANCHOR_END: nextSevenFin
namespace Finny
-- ANCHOR: ArrayFindHelper
def findHelper (arr : Array α) (p : α → Bool) (i : Nat) :
Option (Fin arr.size × α) :=
if h : i < arr.size then
let x := arr[i]
if p x then
some (⟨i, h⟩, x)
else findHelper arr p (i + 1)
else none
-- ANCHOR_END: ArrayFindHelper
-- ANCHOR: ArrayFind
def Array.find (arr : Array α) (p : α → Bool) : Option (Fin arr.size × α) :=
findHelper arr p 0
-- ANCHOR_END: ArrayFind
def arrayMapHelper (f : α → β) (arr : Array α) (soFar : Array β) (i : Fin arr.size) : Array β :=
let nextAccum := soFar.push (f arr[i])
if h : i.val + 1 < arr.size then
have : Array.size arr - (i.val + 1) < Array.size arr - i.val := by
apply Nat.sub_succ_lt_self
exact i.isLt
arrayMapHelper f arr nextAccum ⟨i + 1, h⟩
else
nextAccum
termination_by arr.size - i.val
def Array.map (f : α → β) (arr : Array α) : Array β :=
if h : arr.size > 0 then
arrayMapHelper f arr Array.empty ⟨0, h⟩
else
Array.empty
end Finny |
fp-lean/examples/Examples/ProgramsProofs/InstrumentedInsertionSort.lean | -- ANCHOR: various
example := IO.FS.Stream.getLine
-- ANCHOR_END: various
-- ANCHOR: InstrumentedInsertionSort
def insertSorted [Ord α] (arr : Array α) (i : Fin arr.size) : Array α :=
match i with
| ⟨0, _⟩ => arr
| ⟨i' + 1, _⟩ =>
have : i' < arr.size := by
omega
match Ord.compare arr[i'] arr[i] with
| .lt | .eq => arr
| .gt =>
have : (dbgTraceIfShared "array to swap" arr).size = arr.size := by
simp [dbgTraceIfShared]
insertSorted
((dbgTraceIfShared "array to swap" arr).swap i' i)
⟨i', by simp [*]⟩
theorem insert_sorted_size_eq [Ord α] (len : Nat) (i : Nat) :
(arr : Array α) → (isLt : i < arr.size) → (arr.size = len) →
(insertSorted arr ⟨i, isLt⟩).size = len := by
induction i with
| zero =>
intro arr isLt hLen
simp [insertSorted, *]
| succ i' ih =>
intro arr isLt hLen
simp [insertSorted, dbgTraceIfShared]
split <;> simp [*]
def insertionSortLoop [Ord α] (arr : Array α) (i : Nat) : Array α :=
if h : i < arr.size then
have : (insertSorted arr ⟨i, h⟩).size - (i + 1) < arr.size - i := by
rw [insert_sorted_size_eq arr.size i arr h rfl]
omega
insertionSortLoop (insertSorted arr ⟨i, h⟩) (i + 1)
else
arr
termination_by arr.size - i
def insertionSort [Ord α] (arr : Array α) : Array α :=
insertionSortLoop arr 0
-- ANCHOR_END: InstrumentedInsertionSort
-- ANCHOR: getLines
def getLines : IO (Array String) := do
let stdin ← IO.getStdin
let mut lines : Array String := #[]
let mut currLine ← stdin.getLine
while !currLine.isEmpty do
-- Drop trailing newline:
lines := lines.push (currLine.dropRight 1)
currLine ← stdin.getLine
pure lines
-- ANCHOR_END: getLines
-- ANCHOR: mains
def mainUnique : IO Unit := do
let lines ← getLines
for line in insertionSort lines do
IO.println line
def mainShared : IO Unit := do
let lines ← getLines
IO.println "--- Sorted lines: ---"
for line in insertionSort lines do
IO.println line
IO.println ""
IO.println "--- Original data: ---"
for line in lines do
IO.println line
-- ANCHOR_END: mains
-- ANCHOR: main
def main (args : List String) : IO UInt32 := do
match args with
| ["--shared"] => mainShared; pure 0
| ["--unique"] => mainUnique; pure 0
| _ =>
IO.println "Expected single argument, either \"--shared\" or \"--unique\""
pure 1
-- ANCHOR_END: main |
fp-lean/examples/Examples/ProgramsProofs/Inequalities.lean | import ExampleSupport
-- ANCHOR: various
example := Nat.succ
example := @List.length
section
variable {A B : Prop}
example : Prop := A ∧ B
example := And A B
end
-- ANCHOR_END: various
-- ANCHOR: merge
def merge [Ord α] (xs : List α) (ys : List α) : List α :=
match xs, ys with
| [], _ => ys
| _, [] => xs
| x'::xs', y'::ys' =>
match Ord.compare x' y' with
| .lt | .eq => x' :: merge xs' (y' :: ys')
| .gt => y' :: merge (x'::xs') ys'
-- ANCHOR_END: merge
-- ANCHOR: splitList
def splitList (lst : List α) : (List α × List α) :=
match lst with
| [] => ([], [])
| x :: xs =>
let (a, b) := splitList xs
(x :: b, a)
-- ANCHOR_END: splitList
discarding
/--
error: fail to show termination for
mergeSort
with errors
failed to infer structural recursion:
Not considering parameter α of mergeSort:
it is unchanged in the recursive calls
Not considering parameter #2 of mergeSort:
it is unchanged in the recursive calls
Cannot use parameter xs:
failed to eliminate recursive application
mergeSort halves.fst
Could not find a decreasing measure.
The basic measures relate at each recursive call as follows:
(<, ≤, =: relation proved, ? all proofs failed, _: no proof attempted)
xs #1
1) 70:11-31 ? ?
2) 70:34-54 _ _
#1: xs.length
Please use `termination_by` to specify a decreasing measure.
-/
#check_msgs in
-- ANCHOR: mergeSortNoTerm
def mergeSort [Ord α] (xs : List α) : List α :=
if h : xs.length < 2 then
match xs with
| [] => []
| [x] => [x]
else
let halves := splitList xs
merge (mergeSort halves.fst) (mergeSort halves.snd)
-- ANCHOR_END: mergeSortNoTerm
stop discarding
discarding
/-- error:
failed to prove termination, possible solutions:
- Use `have`-expressions to prove the remaining goals
- Use `termination_by` to specify a different well-founded relation
- Use `decreasing_by` to specify your own tactic for discharging this kind of goal
α : Type u_1
xs : List α
h : ¬xs.length < 2
halves : List α × List α := splitList xs
⊢ (splitList xs).fst.length < xs.length
-/
#check_msgs in
-- ANCHOR: mergeSortGottaProveIt
def mergeSort [Ord α] (xs : List α) : List α :=
if h : xs.length < 2 then
match xs with
| [] => []
| [x] => [x]
else
let halves := splitList xs
merge (mergeSort halves.fst) (mergeSort halves.snd)
termination_by xs.length
-- ANCHOR_END: mergeSortGottaProveIt
stop discarding
-- ANCHOR: splitListEmpty
example : (
splitList []
: (List α × List α)
) = (
([], [])
) := rfl
-- ANCHOR_END: splitListEmpty
-- ANCHOR: splitListOne
example : (
splitList ["basalt"]
) = (
(["basalt"], [])
) := rfl
-- ANCHOR_END: splitListOne
-- ANCHOR: splitListTwo
example : (
splitList ["basalt", "granite"]
) = (
(["basalt"], ["granite"])
) := rfl
-- ANCHOR_END: splitListTwo
--ANCHOR: splitList_shorter_bad_ty
example : ∀(lst : List α), (splitList lst).fst.length < lst.length ∧ (splitList lst).snd.length < lst.length := sorry
--ANCHOR_END: splitList_shorter_bad_ty
discarding
/-- error:
unsolved goals
α : Type u_1
lst : List α
⊢ (splitList lst).fst.length ≤ lst.length ∧ (splitList lst).snd.length ≤ lst.length
-/
#check_msgs in
-- ANCHOR: splitList_shorter_le0
theorem splitList_shorter_le (lst : List α) :
(splitList lst).fst.length ≤ lst.length ∧
(splitList lst).snd.length ≤ lst.length := by
skip
-- ANCHOR_END: splitList_shorter_le0
stop discarding
discarding
/--
error: unsolved goals
case nil
α : Type u_1
⊢ (splitList []).fst.length ≤ [].length ∧ (splitList []).snd.length ≤ [].length
---
error: unsolved goals
case cons
α : Type u_1
x : α
xs : List α
ih : (splitList xs).fst.length ≤ xs.length ∧ (splitList xs).snd.length ≤ xs.length
⊢ (splitList (x :: xs)).fst.length ≤ (x :: xs).length ∧ (splitList (x :: xs)).snd.length ≤ (x :: xs).length
-/
#check_msgs in
-- ANCHOR: splitList_shorter_le1a
theorem splitList_shorter_le (lst : List α) :
(splitList lst).fst.length ≤ lst.length ∧
(splitList lst).snd.length ≤ lst.length := by
induction lst with
| nil => skip
| cons x xs ih => skip
-- ANCHOR_END: splitList_shorter_le1a
stop discarding
discarding
/--
error: unsolved goals
case nil
α : Type u_1
⊢ (splitList []).fst.length ≤ [].length ∧ (splitList []).snd.length ≤ [].length
---
error: unsolved goals
case cons
α : Type u_1
x : α
xs : List α
ih : (splitList xs).fst.length ≤ xs.length ∧ (splitList xs).snd.length ≤ xs.length
⊢ (splitList (x :: xs)).fst.length ≤ (x :: xs).length ∧ (splitList (x :: xs)).snd.length ≤ (x :: xs).length
-/
#check_msgs in
-- ANCHOR: splitList_shorter_le1b
theorem splitList_shorter_le (lst : List α) :
(splitList lst).fst.length ≤ lst.length ∧
(splitList lst).snd.length ≤ lst.length := by
induction lst with
| nil => skip
| cons x xs ih => skip
-- ANCHOR_END: splitList_shorter_le1b
stop discarding
discarding
/-- error:
unsolved goals
case cons
α : Type u_1
x : α
xs : List α
ih : (splitList xs).fst.length ≤ xs.length ∧ (splitList xs).snd.length ≤ xs.length
⊢ (splitList xs).snd.length ≤ xs.length ∧ (splitList xs).fst.length ≤ xs.length + 1
-/
#check_msgs in
-- ANCHOR: splitList_shorter_le2
theorem splitList_shorter_le (lst : List α) :
(splitList lst).fst.length ≤ lst.length ∧
(splitList lst).snd.length ≤ lst.length := by
induction lst with
| nil => simp [splitList]
| cons x xs ih =>
simp [splitList]
-- ANCHOR_END: splitList_shorter_le2
stop discarding
namespace AndDef
-- ANCHOR: And
structure And (a b : Prop) : Prop where
intro ::
left : a
right : b
-- ANCHOR_END: And
-- ANCHOR: AndUse
variable {A B : Prop}
example : A → B → And A B := And.intro
-- ANCHOR_END: AndUse
end AndDef
discarding
/-- error:
unsolved goals
case cons.intro
α : Type u_1
x : α
xs : List α
left✝ : (splitList xs).fst.length ≤ xs.length
right✝ : (splitList xs).snd.length ≤ xs.length
⊢ (splitList xs).snd.length ≤ xs.length ∧ (splitList xs).fst.length ≤ xs.length + 1
-/
#check_msgs in
-- ANCHOR: splitList_shorter_le3
theorem splitList_shorter_le (lst : List α) :
(splitList lst).fst.length ≤ lst.length ∧
(splitList lst).snd.length ≤ lst.length := by
induction lst with
| nil => simp [splitList]
| cons x xs ih =>
simp [splitList]
cases ih
-- ANCHOR_END: splitList_shorter_le3
stop discarding
discarding
/-- error:
unsolved goals
case cons.intro.left
α : Type u_1
x : α
xs : List α
left✝ : (splitList xs).fst.length ≤ xs.length
right✝ : (splitList xs).snd.length ≤ xs.length
⊢ (splitList xs).snd.length ≤ xs.length
case cons.intro.right
α : Type u_1
x : α
xs : List α
left✝ : (splitList xs).fst.length ≤ xs.length
right✝ : (splitList xs).snd.length ≤ xs.length
⊢ (splitList xs).fst.length ≤ xs.length + 1
-/
#check_msgs in
-- ANCHOR: splitList_shorter_le4
theorem splitList_shorter_le (lst : List α) :
(splitList lst).fst.length ≤ lst.length ∧
(splitList lst).snd.length ≤ lst.length := by
induction lst with
| nil => simp [splitList]
| cons x xs ih =>
simp [splitList]
cases ih
constructor
-- ANCHOR_END: splitList_shorter_le4
stop discarding
discarding
/-- error:
unsolved goals
case cons.intro.right
α : Type u_1
x : α
xs : List α
left✝ : (splitList xs).fst.length ≤ xs.length
right✝ : (splitList xs).snd.length ≤ xs.length
⊢ (splitList xs).fst.length ≤ xs.length + 1
-/
#check_msgs in
-- ANCHOR: splitList_shorter_le5
theorem splitList_shorter_le (lst : List α) :
(splitList lst).fst.length ≤ lst.length ∧
(splitList lst).snd.length ≤ lst.length := by
induction lst with
| nil => simp [splitList]
| cons x xs ih =>
simp [splitList]
cases ih
constructor
case left => assumption
-- ANCHOR_END: splitList_shorter_le5
stop discarding
namespace Extras
discarding
/-- error:
unsolved goals
n m : Nat
⊢ n ≤ m → n ≤ m + 1
-/
#check_msgs in
-- ANCHOR: le_succ_of_le0
theorem Nat.le_succ_of_le : n ≤ m → n ≤ m + 1 := by
skip
-- ANCHOR_END: le_succ_of_le0
-- ANCHOR: le_succ_of_le_statement
example : ∀(n m : Nat), n ≤ m → n ≤ m + 1 := @Nat.le_succ_of_le
-- ANCHOR_END: le_succ_of_le_statement
stop discarding
-- ANCHOR: Nat.le_ctors
section
open Nat.le
example := @step
example := @refl
end
-- ANCHOR_END: Nat.le_ctors
-- ANCHOR: Nat.lt_imp
example {n m : Nat} : n + 1 < m + 1 → n < m := by simp
-- ANCHOR_END: Nat.lt_imp
discarding
/-- error:
unsolved goals
n m : Nat
h : n ≤ m
⊢ n ≤ m + 1
-/
#check_msgs in
-- ANCHOR: le_succ_of_le1
theorem Nat.le_succ_of_le : n ≤ m → n ≤ m + 1 := by
intro h
-- ANCHOR_END: le_succ_of_le1
stop discarding
discarding
/--
error: unsolved goals
case refl
n m : Nat
⊢ n ≤ n + 1
---
error: unsolved goals
case step
n m m✝ : Nat
a✝ : n.le m✝
ih : n ≤ m✝ + 1
⊢ n ≤ m✝.succ + 1
-/
#check_msgs in
-- ANCHOR: le_succ_of_le2a
theorem Nat.le_succ_of_le : n ≤ m → n ≤ m + 1 := by
intro h
induction h with
| refl => skip
| step _ ih => skip
-- ANCHOR_END: le_succ_of_le2a
stop discarding
discarding
/--
error: unsolved goals
case refl
n m : Nat
⊢ n ≤ n + 1
---
error: unsolved goals
case step
n m m✝ : Nat
a✝ : n.le m✝
ih : n ≤ m✝ + 1
⊢ n ≤ m✝.succ + 1
-/
#check_msgs in
-- ANCHOR: le_succ_of_le2b
theorem Nat.le_succ_of_le : n ≤ m → n ≤ m + 1 := by
intro h
induction h with
| refl => skip
| step _ ih => skip
-- ANCHOR_END: le_succ_of_le2b
stop discarding
discarding
/--
error: unsolved goals
case refl.a
n m : Nat
⊢ n.le n
---
error: unsolved goals
case step
n m m✝ : Nat
a✝ : n.le m✝
ih : n ≤ m✝ + 1
⊢ n ≤ m✝.succ + 1
-/
#check_msgs in
-- ANCHOR: le_succ_of_le3
theorem Nat.le_succ_of_le : n ≤ m → n ≤ m + 1 := by
intro h
induction h with
| refl => constructor
| step _ ih => skip
-- ANCHOR_END: le_succ_of_le3
stop discarding
discarding
/-- error:
unsolved goals
case step
n m m✝ : Nat
a✝ : n.le m✝
ih : n ≤ m✝ + 1
⊢ n ≤ m✝.succ + 1
-/
#check_msgs in
-- ANCHOR: le_succ_of_le4
theorem Nat.le_succ_of_le : n ≤ m → n ≤ m + 1 := by
intro h
induction h with
| refl => constructor; constructor
| step _ ih => skip
-- ANCHOR_END: le_succ_of_le4
stop discarding
discarding
/-- error:
unsolved goals
case step.a
n m m✝ : Nat
a✝ : n.le m✝
ih : n ≤ m✝ + 1
⊢ n.le (m✝ + 1)
-/
#check_msgs in
-- ANCHOR: le_succ_of_le5
theorem Nat.le_succ_of_le : n ≤ m → n ≤ m + 1 := by
intro h
induction h with
| refl => constructor; constructor
| step _ ih => constructor
-- ANCHOR_END: le_succ_of_le5
stop discarding
-- ANCHOR: le_succ_of_le
theorem Nat.le_succ_of_le : n ≤ m → n ≤ m + 1 := by
intro h
induction h with
| refl => constructor; constructor
| step => constructor; assumption
-- ANCHOR_END: le_succ_of_le
namespace Apply
-- ANCHOR: le_succ_of_le_apply
theorem Nat.le_succ_of_le : n ≤ m → n ≤ m + 1 := by
intro h
induction h with
| refl => apply Nat.le.step; exact Nat.le.refl
| step _ ih => apply Nat.le.step; exact ih
-- ANCHOR_END: le_succ_of_le_apply
end Apply
namespace Golf
-- ANCHOR: le_succ_of_le_golf
theorem Nat.le_succ_of_le (h : n ≤ m) : n ≤ m + 1:= by
induction h <;> repeat (first | constructor | assumption)
-- ANCHOR_END: le_succ_of_le_golf
end Golf
namespace Golf'
-- ANCHOR: le_succ_of_le_grind
theorem Nat.le_succ_of_le (h : n ≤ m) : n ≤ m + 1:= by
grind
-- ANCHOR_END: le_succ_of_le_grind
end Golf'
namespace NoTac
-- ANCHOR: le_succ_of_le_recursive
theorem Nat.le_succ_of_le : n ≤ m → n ≤ m + 1
| .refl => .step .refl
| .step h => .step (Nat.le_succ_of_le h)
-- ANCHOR_END: le_succ_of_le_recursive
end NoTac
end Extras
discarding
-- ANCHOR: splitList_shorter_le
theorem splitList_shorter_le (lst : List α) :
(splitList lst).fst.length ≤ lst.length ∧
(splitList lst).snd.length ≤ lst.length := by
induction lst with
| nil => simp [splitList]
| cons x xs ih =>
simp [splitList]
cases ih
constructor
case left => assumption
case right =>
apply Nat.le_succ_of_le
assumption
-- ANCHOR_END: splitList_shorter_le
stop discarding
discarding
/--
error: unsolved goals
case case1
α : Type u_1
⊢ ([], []).fst.length ≤ [].length ∧ ([], []).snd.length ≤ [].length
---
error: unsolved goals
case case2
α : Type u_1
x : α
xs a b : List α
splitEq : splitList xs = (a, b)
ih : (splitList xs).fst.length ≤ xs.length ∧ (splitList xs).snd.length ≤ xs.length
⊢ (x :: b, a).fst.length ≤ (x :: xs).length ∧ (x :: b, a).snd.length ≤ (x :: xs).length
-/
#check_msgs in
-- ANCHOR: splitList_shorter_le_funInd1
theorem splitList_shorter_le (lst : List α) :
(splitList lst).fst.length ≤ lst.length ∧
(splitList lst).snd.length ≤ lst.length := by
fun_induction splitList with
| case1 => skip
| case2 x xs a b splitEq ih => skip
-- ANCHOR_END: splitList_shorter_le_funInd1
stop discarding
-- ANCHOR: splitList_shorter_le_funInd2
theorem splitList_shorter_le (lst : List α) :
(splitList lst).fst.length ≤ lst.length ∧
(splitList lst).snd.length ≤ lst.length := by
fun_induction splitList <;> grind
-- ANCHOR_END: splitList_shorter_le_funInd2
discarding
/-- error:
unsolved goals
α : Type u_1
lst : List α
x✝ : lst.length ≥ 2
⊢ (splitList lst).fst.length < lst.length ∧ (splitList lst).snd.length < lst.length
-/
#check_msgs in
-- ANCHOR: splitList_shorter_start
theorem splitList_shorter (lst : List α) (_ : lst.length ≥ 2) :
(splitList lst).fst.length < lst.length ∧
(splitList lst).snd.length < lst.length := by
skip
-- ANCHOR_END: splitList_shorter_start
stop discarding
discarding
/-- error:
unsolved goals
α : Type u_1
lst : List α
x y : α
xs : List α
x✝ : (x :: y :: xs).length ≥ 2
⊢ (splitList (x :: y :: xs)).fst.length < (x :: y :: xs).length ∧
(splitList (x :: y :: xs)).snd.length < (x :: y :: xs).length
-/
#check_msgs in
-- ANCHOR: splitList_shorter_1
theorem splitList_shorter (lst : List α) (_ : lst.length ≥ 2) :
(splitList lst).fst.length < lst.length ∧
(splitList lst).snd.length < lst.length := by
match lst with
| x :: y :: xs =>
skip
-- ANCHOR_END: splitList_shorter_1
stop discarding
discarding
/-- error:
unsolved goals
α : Type u_1
lst : List α
x y : α
xs : List α
x✝ : (x :: y :: xs).length ≥ 2
⊢ (splitList xs).fst.length < xs.length + 1 ∧ (splitList xs).snd.length < xs.length + 1
-/
#check_msgs in
-- ANCHOR: splitList_shorter_2
theorem splitList_shorter (lst : List α) (_ : lst.length ≥ 2) :
(splitList lst).fst.length < lst.length ∧
(splitList lst).snd.length < lst.length := by
match lst with
| x :: y :: xs =>
simp [splitList]
-- ANCHOR_END: splitList_shorter_2
stop discarding
discarding
/-- error:
unsolved goals
α : Type u_1
lst : List α
x y : α
xs : List α
x✝ : (x :: y :: xs).length ≥ 2
⊢ (splitList xs).fst.length ≤ xs.length ∧ (splitList xs).snd.length ≤ xs.length
-/
#check_msgs in
-- ANCHOR: splitList_shorter_2b
theorem splitList_shorter (lst : List α) (_ : lst.length ≥ 2) :
(splitList lst).fst.length < lst.length ∧
(splitList lst).snd.length < lst.length := by
match lst with
| x :: y :: xs =>
simp +arith [splitList]
-- ANCHOR_END: splitList_shorter_2b
stop discarding
-- ANCHOR: splitList_shorter
theorem splitList_shorter (lst : List α) (_ : lst.length ≥ 2) :
(splitList lst).fst.length < lst.length ∧
(splitList lst).snd.length < lst.length := by
match lst with
| x :: y :: xs =>
simp +arith [splitList]
apply splitList_shorter_le
-- ANCHOR_END: splitList_shorter
-- ANCHOR: splitList_shorter_sides
theorem splitList_shorter_fst (lst : List α) (h : lst.length ≥ 2) :
(splitList lst).fst.length < lst.length :=
splitList_shorter lst h |>.left
theorem splitList_shorter_snd (lst : List α) (h : lst.length ≥ 2) :
(splitList lst).snd.length < lst.length :=
splitList_shorter lst h |>.right
-- ANCHOR_END: splitList_shorter_sides
discarding
/--
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
-/
#check_msgs in
--ANCHOR: mergeSortSorry
def mergeSort [Ord α] (xs : List α) : List α :=
if h : xs.length < 2 then
match xs with
| [] => []
| [x] => [x]
else
let halves := splitList xs
have : halves.fst.length < xs.length := by
sorry
have : halves.snd.length < xs.length := by
sorry
merge (mergeSort halves.fst) (mergeSort halves.snd)
termination_by xs.length
--ANCHOR_END: mergeSortSorry
stop discarding
discarding
/--
error: unsolved goals
case h
α : Type ?u.72443
inst✝ : Ord α
xs : List α
h : ¬xs.length < 2
halves : List α × List α := ⋯
⊢ xs.length ≥ 2
---
error: unsolved goals
case h
α : Type ?u.72443
inst✝ : Ord α
xs : List α
h : ¬xs.length < 2
halves : List α × List α := ⋯
this : halves.fst.length < xs.length
⊢ xs.length ≥ 2
-/
#check_msgs in
-- ANCHOR: mergeSortNeedsGte
def mergeSort [Ord α] (xs : List α) : List α :=
if h : xs.length < 2 then
match xs with
| [] => []
| [x] => [x]
else
let halves := splitList xs
have : halves.fst.length < xs.length := by
apply splitList_shorter_fst
have : halves.snd.length < xs.length := by
apply splitList_shorter_snd
merge (mergeSort halves.fst) (mergeSort halves.snd)
termination_by xs.length
-- ANCHOR_END: mergeSortNeedsGte
stop discarding
discarding
/--
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
-/
#check_msgs in
-- ANCHOR: mergeSortGteStarted
def mergeSort [Ord α] (xs : List α) : List α :=
if h : xs.length < 2 then
match xs with
| [] => []
| [x] => [x]
else
let halves := splitList xs
have : xs.length ≥ 2 := by sorry
have : halves.fst.length < xs.length := by
apply splitList_shorter_fst
assumption
have : halves.snd.length < xs.length := by
apply splitList_shorter_snd
assumption
merge (mergeSort halves.fst) (mergeSort halves.snd)
termination_by xs.length
-- ANCHOR_END: mergeSortGteStarted
stop discarding
-- ANCHOR: mergeSort
def mergeSort [Ord α] (xs : List α) : List α :=
if h : xs.length < 2 then
match xs with
| [] => []
| [x] => [x]
else
let halves := splitList xs
have : xs.length ≥ 2 := by
grind
have : halves.fst.length < xs.length := by
apply splitList_shorter_fst
assumption
have : halves.snd.length < xs.length := by
apply splitList_shorter_snd
assumption
merge (mergeSort halves.fst) (mergeSort halves.snd)
termination_by xs.length
-- ANCHOR_END: mergeSort
/-- info:
["geode", "limestone", "mica", "soapstone"]
-/
#check_msgs in
-- ANCHOR: mergeSortRocks
#eval mergeSort ["soapstone", "geode", "mica", "limestone"]
-- ANCHOR_END: mergeSortRocks
/-- info:
[3, 5, 15, 22]
-/
#check_msgs in
-- ANCHOR: mergeSortNumbers
#eval mergeSort [5, 3, 22, 15]
-- ANCHOR_END: mergeSortNumbers
theorem zero_lt_succ : 0 < Nat.succ n := by
induction n with
| zero => constructor
| succ n' ih => constructor; exact ih
namespace Proofs
theorem Nat.succ_sub_succ_eq_sub (n m : Nat) : Nat.succ n - Nat.succ m = n - m := by simp
theorem sub_le (n k : Nat) : n - k ≤ n := by
induction k with
| zero => simp
| succ k' ih =>
calc
n - Nat.succ k' ≤ n - k' := by apply Nat.pred_le
n - k' ≤ n := ih
-- def sub_lt (n k : Nat) : ¬ n < k → n - k < n := by
-- induction k with
-- | zero => intro h
-- def divide (n k : Nat) (nonZero : k ≠ 0) : Nat :=
-- if hLt : n < k then
-- 0
-- else
-- have : n - k < n := by
-- apply Nat.sub_lt
-- . cases k with
-- | zero => contradiction
-- | succ k' =>
-- 1 + divide (n - k) k nonZero
-- termination_by divide n k _ => n
theorem Nat.lt_of_succ_lt : n + 1 < m → n < m := by
intro h
induction h with
| refl => repeat constructor
| step => constructor; assumption
theorem Nat.sub_self_zero (n : Nat) : n - n = 0 := by
cases n <;> simp
theorem not_eq_zero_of_lt (h : b < a) : a ≠ 0 := by
cases h <;> simp
theorem Nat.add_succ (n k : Nat) : n + k.succ = (n + k).succ := by
rfl
theorem Nat.sub_succ (n k : Nat) : n - k.succ = (n - k).pred := by
rfl
theorem Nat.sub_zero (n : Nat) : n - 0 = n := by rfl
theorem Nat.pred_lt (n : Nat) : n ≠ 0 → n.pred < n := by
intro h
cases n <;> simp_all
theorem Nat.not_eq_zero_of_lt (n k : Nat) : n < k → k ≠ 0 := by
intro h
cases h <;> simp
theorem Nat.sub_succ_lt_self (a i : Nat) : i < a → a - (i + 1) < a - i := by
intro h
rw [Nat.add_succ, Nat.sub_succ]
apply Nat.pred_lt
apply Nat.not_eq_zero_of_lt
apply Nat.zero_lt_sub_of_lt
assumption
end Proofs |
fp-lean/examples/Examples/ProgramsProofs/InsertionSort.lean | import ExampleSupport
/-- info:
dbgTraceIfShared.{u} {α : Type u} (s : String) (a : α) : α
-/
#check_msgs in
-- ANCHOR: dbgTraceIfSharedSig
#check dbgTraceIfShared
-- ANCHOR_END: dbgTraceIfSharedSig
discarding
/-- error:
unsolved goals
α : Type ?u.7
inst✝ : Ord α
arr : Array α
i : Fin arr.size
i' : Nat
isLt✝ : i' + 1 < arr.size
⊢ i' < arr.size
-/
#check_msgs in
-- ANCHOR: insertSortedNoProof
def insertSorted [Ord α] (arr : Array α) (i : Fin arr.size) : Array α :=
match i with
| ⟨0, _⟩ => arr
| ⟨i' + 1, _⟩ =>
match Ord.compare arr[i'] arr[i] with
| .lt | .eq => arr
| .gt =>
insertSorted (arr.swap i' i) ⟨i', by simp [*]⟩
-- ANCHOR_END: insertSortedNoProof
stop discarding
/-- info:
Nat.lt_of_succ_lt {n m : Nat} : n.succ < m → n < m
-/
#check_msgs in
-- ANCHOR: lt_of_succ_lt_type
#check Nat.lt_of_succ_lt
-- ANCHOR_END: lt_of_succ_lt_type
-- Precondition: array positions 0 .. i-1 are sorted
-- Postcondition: array positions 0 .. i are sorted
-- ANCHOR: insertSorted
def insertSorted [Ord α] (arr : Array α) (i : Fin arr.size) : Array α :=
match i with
| ⟨0, _⟩ => arr
| ⟨i' + 1, _⟩ =>
have : i' < arr.size := by
grind
match Ord.compare arr[i'] arr[i] with
| .lt | .eq => arr
| .gt =>
insertSorted (arr.swap i' i) ⟨i', by simp [*]⟩
-- ANCHOR_END: insertSorted
-- theorem insert_sorted_size_eq' [Ord α] (len : Nat) (i : Nat) :
-- (arr : Array α) → (isLt : i < arr.size) →
-- arr.size = (insertSorted arr ⟨i, isLt⟩).size := by
-- induction i with
-- | zero =>
-- intro arr isLt
-- simp [insertSorted, *]
-- | succ i' ih =>
-- intro arr isLt
-- simp [insertSorted]
-- split <;> simp [*]
discarding
/-- error:
unsolved goals
case succ
α : Type u_1
inst✝ : Ord α
arr : Array α
i : Fin arr.size
j' : Nat
ih : ∀ (isLt : j' < arr.size), (insertSorted arr ⟨j', isLt⟩).size = arr.size
isLt : j' + 1 < arr.size
⊢ (match compare arr[j'] arr[j' + 1] with
| Ordering.lt => arr
| Ordering.eq => arr
| Ordering.gt => insertSorted (arr.swap j' (j' + 1) ⋯ ⋯) ⟨j', ⋯⟩).size =
arr.size
-/
#check_msgs in
-- ANCHOR: insert_sorted_size_eq_0
theorem insert_sorted_size_eq [Ord α] (arr : Array α) (i : Fin arr.size) :
(insertSorted arr i).size = arr.size := by
match i with
| ⟨j, isLt⟩ =>
induction j with
| zero => simp [insertSorted]
| succ j' ih =>
simp [insertSorted]
-- ANCHOR_END: insert_sorted_size_eq_0
stop discarding
discarding
/--
error: unsolved goals
case h_1
α : Type u_1
inst✝ : Ord α
arr : Array α
i : Fin arr.size
j' : Nat
ih : ∀ (isLt : j' < arr.size), (insertSorted arr ⟨j', isLt⟩).size = arr.size
isLt : j' + 1 < arr.size
x✝ : Ordering
heq✝ : compare arr[j'] arr[j' + 1] = Ordering.lt
⊢ arr.size = arr.size
case h_2
α : Type u_1
inst✝ : Ord α
arr : Array α
i : Fin arr.size
j' : Nat
ih : ∀ (isLt : j' < arr.size), (insertSorted arr ⟨j', isLt⟩).size = arr.size
isLt : j' + 1 < arr.size
x✝ : Ordering
heq✝ : compare arr[j'] arr[j' + 1] = Ordering.eq
⊢ arr.size = arr.size
case h_3
α : Type u_1
inst✝ : Ord α
arr : Array α
i : Fin arr.size
j' : Nat
ih : ∀ (isLt : j' < arr.size), (insertSorted arr ⟨j', isLt⟩).size = arr.size
isLt : j' + 1 < arr.size
x✝ : Ordering
heq✝ : compare arr[j'] arr[j' + 1] = Ordering.gt
⊢ (insertSorted (arr.swap j' (j' + 1) ⋯ ⋯) ⟨j', ⋯⟩).size = arr.size
-/
#check_msgs in
-- ANCHOR: insert_sorted_size_eq_1
theorem insert_sorted_size_eq [Ord α] (arr : Array α) (i : Fin arr.size) :
(insertSorted arr i).size = arr.size := by
match i with
| ⟨j, isLt⟩ =>
induction j with
| zero => simp [insertSorted]
| succ j' ih =>
simp [insertSorted]
split
-- ANCHOR_END: insert_sorted_size_eq_1
stop discarding
discarding
/--
error: unsolved goals
case h_3
α : Type u_1
inst✝ : Ord α
arr : Array α
i : Fin arr.size
j' : Nat
ih : ∀ (isLt : j' < arr.size), (insertSorted arr ⟨j', isLt⟩).size = arr.size
isLt : j' + 1 < arr.size
x✝ : Ordering
heq✝ : compare arr[j'] arr[j' + 1] = Ordering.gt
⊢ (insertSorted (arr.swap j' (j' + 1) ⋯ ⋯) ⟨j', ⋯⟩).size = arr.size
-/
#check_msgs in
-- ANCHOR: insert_sorted_size_eq_2
theorem insert_sorted_size_eq [Ord α] (arr : Array α) (i : Fin arr.size) :
(insertSorted arr i).size = arr.size := by
match i with
| ⟨j, isLt⟩ =>
induction j with
| zero => simp [insertSorted]
| succ j' ih =>
simp [insertSorted]
split <;> try rfl
-- ANCHOR_END: insert_sorted_size_eq_2
stop discarding
discarding
/--
error: unsolved goals
case h_3
α : Type u_1
inst✝ : Ord α
j' : Nat
ih : ∀ (arr : Array α) (i : Fin arr.size) (isLt : j' < arr.size), (insertSorted arr ⟨j', isLt⟩).size = arr.size
arr : Array α
i : Fin arr.size
isLt : j' + 1 < arr.size
x✝ : Ordering
heq✝ : compare arr[j'] arr[j' + 1] = Ordering.gt
⊢ (insertSorted (arr.swap j' (j' + 1) ⋯ ⋯) ⟨j', ⋯⟩).size = arr.size
-/
#check_msgs in
-- ANCHOR: insert_sorted_size_eq_3
theorem insert_sorted_size_eq [Ord α] (arr : Array α) (i : Fin arr.size) :
(insertSorted arr i).size = arr.size := by
match i with
| ⟨j, isLt⟩ =>
induction j generalizing arr with
| zero => simp [insertSorted]
| succ j' ih =>
simp [insertSorted]
split <;> try rfl
-- ANCHOR_END: insert_sorted_size_eq_3
stop discarding
discarding
/--
error: unsolved goals
case case1
α : Type u_1
inst✝ : Ord α
arr✝ arr : Array α
isLt : 0 < arr.size
⊢ arr.size = arr.size
---
error: unsolved goals
case case2
α : Type u_1
inst✝ : Ord α
arr✝ arr : Array α
i : Nat
isLt✝ : i + 1 < arr.size
this : i < arr.size
isLt : compare arr[i] arr[⟨i.succ, isLt✝⟩] = Ordering.lt
⊢ (match compare arr[i] arr[⟨i.succ, isLt✝⟩] with
| Ordering.lt => arr
| Ordering.eq => arr
| Ordering.gt => insertSorted (arr.swap i (↑⟨i.succ, isLt✝⟩) this ⋯) ⟨i, ⋯⟩).size =
arr.size
---
error: unsolved goals
case case3
α : Type u_1
inst✝ : Ord α
arr✝ arr : Array α
i : Nat
isLt : i + 1 < arr.size
this : i < arr.size
isEq : compare arr[i] arr[⟨i.succ, isLt⟩] = Ordering.eq
⊢ (match compare arr[i] arr[⟨i.succ, isLt⟩] with
| Ordering.lt => arr
| Ordering.eq => arr
| Ordering.gt => insertSorted (arr.swap i (↑⟨i.succ, isLt⟩) this ⋯) ⟨i, ⋯⟩).size =
arr.size
---
error: unsolved goals
case case4
α : Type u_1
inst✝ : Ord α
arr✝ arr : Array α
i : Nat
isLt : i + 1 < arr.size
this : i < arr.size
isGt : compare arr[i] arr[⟨i.succ, isLt⟩] = Ordering.gt
ih : (insertSorted (arr.swap i (↑⟨i.succ, isLt⟩) this ⋯) ⟨i, ⋯⟩).size = (arr.swap i (↑⟨i.succ, isLt⟩) this ⋯).size
⊢ (match compare arr[i] arr[⟨i.succ, isLt⟩] with
| Ordering.lt => arr
| Ordering.eq => arr
| Ordering.gt => insertSorted (arr.swap i (↑⟨i.succ, isLt⟩) this ⋯) ⟨i, ⋯⟩).size =
arr.size
-/
#check_msgs in
-- ANCHOR: insert_sorted_size_eq_funInd1
theorem insert_sorted_size_eq [Ord α]
(arr : Array α) (i : Fin arr.size) :
(insertSorted arr i).size = arr.size := by
fun_induction insertSorted with
| case1 arr isLt => skip
| case2 arr i isLt this isLt => skip
| case3 arr i isLt this isEq => skip
| case4 arr i isLt this isGt ih => skip
-- ANCHOR_END: insert_sorted_size_eq_funInd1
stop discarding
-- ANCHOR: insert_sorted_size_eq_funInd
theorem insert_sorted_size_eq [Ord α]
(arr : Array α) (i : Fin arr.size) :
(insertSorted arr i).size = arr.size := by
fun_induction insertSorted <;> grind [Array.size_swap]
-- ANCHOR_END: insert_sorted_size_eq_funInd
discarding
/--
error: fail to show termination for
insertionSortLoop
with errors
failed to infer structural recursion:
Not considering parameter α of insertionSortLoop:
it is unchanged in the recursive calls
Not considering parameter #2 of insertionSortLoop:
it is unchanged in the recursive calls
Cannot use parameter arr:
the type Array α does not have a `.brecOn` recursor
Cannot use parameter i:
failed to eliminate recursive application
insertionSortLoop (insertSorted arr ⟨i, h⟩) (i + 1)
Could not find a decreasing measure.
The basic measures relate at each recursive call as follows:
(<, ≤, =: relation proved, ? all proofs failed, _: no proof attempted)
arr i #1
1) 324:4-55 ? ? ?
#1: arr.size - i
Please use `termination_by` to specify a decreasing measure.
-/
#check_msgs in
-- ANCHOR: insertionSortLoopTermination
def insertionSortLoop [Ord α] (arr : Array α) (i : Nat) : Array α :=
if h : i < arr.size then
insertionSortLoop (insertSorted arr ⟨i, h⟩) (i + 1)
else
arr
-- ANCHOR_END: insertionSortLoopTermination
stop discarding
namespace Partial
-- ANCHOR: partialInsertionSortLoop
partial def insertionSortLoop [Ord α] (arr : Array α) (i : Nat) : Array α :=
if h : i < arr.size then
insertionSortLoop (insertSorted arr ⟨i, h⟩) (i + 1)
else
arr
-- ANCHOR_END: partialInsertionSortLoop
/-- info:
#[3, 5, 8, 17]
-/
#check_msgs in
-- ANCHOR: insertionSortPartialOne
#eval insertionSortLoop #[5, 17, 3, 8] 0
-- ANCHOR_END: insertionSortPartialOne
/-- info:
#["igneous", "metamorphic", "sedimentary"]
-/
#check_msgs in
-- ANCHOR: insertionSortPartialTwo
#eval insertionSortLoop #["metamorphic", "igneous", "sedimentary"] 0
-- ANCHOR_END: insertionSortPartialTwo
end Partial
discarding
/-- error:
failed to prove termination, possible solutions:
- Use `have`-expressions to prove the remaining goals
- Use `termination_by` to specify a different well-founded relation
- Use `decreasing_by` to specify your own tactic for discharging this kind of goal
α : Type u_1
inst✝ : Ord α
arr : Array α
i : Nat
h : i < arr.size
⊢ (insertSorted arr ⟨i, h⟩).size - (i + 1) < arr.size - i
-/
#check_msgs in
-- ANCHOR: insertionSortLoopProof1
def insertionSortLoop [Ord α] (arr : Array α) (i : Nat) : Array α :=
if h : i < arr.size then
insertionSortLoop (insertSorted arr ⟨i, h⟩) (i + 1)
else
arr
termination_by arr.size - i
-- ANCHOR_END: insertionSortLoopProof1
stop discarding
discarding
/--
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
---
warning: declaration uses 'sorry'
-/
#check_msgs in
--ANCHOR: insertionSortLoopSorry
def insertionSortLoop [Ord α] (arr : Array α) (i : Nat) : Array α :=
if h : i < arr.size then
have : (insertSorted arr ⟨i, h⟩).size - (i + 1) < arr.size - i := by
sorry
insertionSortLoop (insertSorted arr ⟨i, h⟩) (i + 1)
else
arr
termination_by arr.size - i
--ANCHOR_END: insertionSortLoopSorry
stop discarding
discarding
/-- error:
unsolved goals
α : Type ?u.23737
inst✝ : Ord α
arr : Array α
i : Nat
h : i < arr.size
⊢ arr.size - (i + 1) < arr.size - i
-/
#check_msgs in
-- ANCHOR: insertionSortLoopRw
def insertionSortLoop [Ord α] (arr : Array α) (i : Nat) : Array α :=
if h : i < arr.size then
have : (insertSorted arr ⟨i, h⟩).size - (i + 1) < arr.size - i := by
rw [insert_sorted_size_eq]
insertionSortLoop (insertSorted arr ⟨i, h⟩) (i + 1)
else
arr
termination_by arr.size - i
-- ANCHOR_END: insertionSortLoopRw
stop discarding
-- ANCHOR: sub_succ_lt_self_type
example : ∀ (a i : Nat), i < a → a - (i + 1) < a - i := Nat.sub_succ_lt_self
-- ANCHOR_END: sub_succ_lt_self_type
-- ANCHOR: insertionSortLoop
def insertionSortLoop [Ord α] (arr : Array α) (i : Nat) : Array α :=
if h : i < arr.size then
have : (insertSorted arr ⟨i, h⟩).size - (i + 1) < arr.size - i := by
grind [insert_sorted_size_eq]
insertionSortLoop (insertSorted arr ⟨i, h⟩) (i + 1)
else
arr
termination_by arr.size - i
-- ANCHOR_END: insertionSortLoop
-- ANCHOR: insertionSort
def insertionSort [Ord α] (arr : Array α) : Array α :=
insertionSortLoop arr 0
-- ANCHOR_END: insertionSort
-- ANCHOR: names
example := @List.map
example := @Array.swap
example := (@Array.swap : {α : Type _} → (xs : Array α) → (i j : Nat) → (h1 : autoParam (i < xs.size) _) → (h2 : autoParam (j < xs.size) _) → Array α)
example : Fin 1 := {val := 0, isLt := by grind}
example := @Array.set
example {n} := Fin n
example := Fin 0
section
variable (arr : Array α)
example := Fin arr.size
example := OfNat
/-- warning: declaration uses 'sorry' -/
#guard_msgs in
theorem ohNoNotReallyTrue : 3 < 2 := by sorry
end
-- ANCHOR_END: names
/-- info:
#[1, 3, 4, 7]
-/
#check_msgs in
-- ANCHOR: insertionSortNums
#eval insertionSort #[3, 1, 7, 4]
-- ANCHOR_END: insertionSortNums
/-- info:
#["granite", "hematite", "marble", "quartz"]
-/
#check_msgs in
-- ANCHOR: insertionSortStrings
#eval insertionSort #[ "quartz", "marble", "granite", "hematite"]
-- ANCHOR_END: insertionSortStrings
--ANCHOR: etc
example := @Array.map
--ANCHOR_END: etc |
fp-lean/examples/Examples/ProgramsProofs/TCOTest.lean | import Examples.ProgramsProofs.TCO
def main : IO Unit := do
let stdout ← IO.getStdout
IO.println "Start"
stdout.flush
let theBigList := bigList 100000000 []
IO.println "One"
stdout.flush
IO.println theBigList.length
IO.println (Tail.sum theBigList)
-- IO.println "Two"
-- stdout.flush
-- IO.println (NonTail.sum theBigList) |
fp-lean/examples/Examples/ProgramsProofs/TCO.lean | import ExampleSupport
import Examples.Monads.Conveniences
-- ANCHOR: NonTailSum
def NonTail.sum : List Nat → Nat
| [] => 0
| x :: xs => x + sum xs
-- ANCHOR_END: NonTailSum
evaluation steps : Nat {{{ NonTailSumOneTwoThree }}}
-- ANCHOR: NonTailSumOneTwoThree
NonTail.sum [1, 2, 3]
===>
1 + (NonTail.sum [2, 3])
===>
1 + (2 + (NonTail.sum [3]))
===>
1 + (2 + (3 + (NonTail.sum [])))
===>
1 + (2 + (3 + 0))
===>
1 + (2 + 3)
===>
1 + 5
===>
6
-- ANCHOR_END: NonTailSumOneTwoThree
end evaluation steps
namespace MoreClear
-- ANCHOR: MoreClearSumHelper
def Tail.sumHelper (soFar : Nat) : List Nat → Nat
| [] => soFar + 0
| x :: xs => sumHelper (x + soFar) xs
-- ANCHOR_END: MoreClearSumHelper
end MoreClear
-- ANCHOR: TailSum
def Tail.sumHelper (soFar : Nat) : List Nat → Nat
| [] => soFar
| x :: xs => sumHelper (x + soFar) xs
def Tail.sum (xs : List Nat) : Nat :=
Tail.sumHelper 0 xs
-- ANCHOR_END: TailSum
evaluation steps : Nat {{{ TailSumOneTwoThree }}}
-- ANCHOR: TailSumOneTwoThree
Tail.sum [1, 2, 3]
===>
Tail.sumHelper 0 [1, 2, 3]
===>
Tail.sumHelper (0 + 1) [2, 3]
===>
Tail.sumHelper 1 [2, 3]
===>
Tail.sumHelper (1 + 2) [3]
===>
Tail.sumHelper 3 [3]
===>
Tail.sumHelper (3 + 3) []
===>
Tail.sumHelper 6 []
===>
6
-- ANCHOR_END: TailSumOneTwoThree
end evaluation steps
-- ANCHOR: NonTailReverse
def NonTail.reverse : List α → List α
| [] => []
| x :: xs => reverse xs ++ [x]
-- ANCHOR_END: NonTailReverse
evaluation steps {{{ NonTailReverseSteps }}}
-- ANCHOR: NonTailReverseSteps
NonTail.reverse [1, 2, 3]
===>
(NonTail.reverse [2, 3]) ++ [1]
===>
((NonTail.reverse [3]) ++ [2]) ++ [1]
===>
(((NonTail.reverse []) ++ [3]) ++ [2]) ++ [1]
===>
(([] ++ [3]) ++ [2]) ++ [1]
===>
([3] ++ [2]) ++ [1]
===>
[3, 2] ++ [1]
===>
[3, 2, 1]
-- ANCHOR_END: NonTailReverseSteps
end evaluation steps
-- ANCHOR: TailReverse
def Tail.reverseHelper (soFar : List α) : List α → List α
| [] => soFar
| x :: xs => reverseHelper (x :: soFar) xs
def Tail.reverse (xs : List α) : List α :=
Tail.reverseHelper [] xs
-- ANCHOR_END: TailReverse
evaluation steps {{{ TailReverseSteps }}}
-- ANCHOR: TailReverseSteps
Tail.reverse [1, 2, 3]
===>
Tail.reverseHelper [] [1, 2, 3]
===>
Tail.reverseHelper [1] [2, 3]
===>
Tail.reverseHelper [2, 1] [3]
===>
Tail.reverseHelper [3, 2, 1] []
===>
[3, 2, 1]
-- ANCHOR_END: TailReverseSteps
end evaluation steps
def Slow.mirror : BinTree α → BinTree α
| .leaf => .leaf
| .branch l x r => .branch (mirror r) x (mirror l)
def CPS.mirror {β : Type u} (k : BinTree α → β) : BinTree α → β
| .leaf => k .leaf
| .branch l x r =>
mirror (fun r' => mirror (fun l' => k (.branch r' x l')) l) r
def CPS.reverse (k : List α → β) : List α → β
| [] => k []
| x :: xs => reverse (fun xs' => k (xs' ++ [x])) xs
deriving instance Repr for BinTree
#eval CPS.mirror id (.branch (.branch .leaf 1 .leaf) 4 (.branch (.branch .leaf 2 .leaf) 3 .leaf))
theorem mirror_cps_eq' : @CPS.mirror α (BinTree α) f = f ∘ @Slow.mirror α := by
funext t
induction t generalizing f with
| leaf => simp [Slow.mirror, CPS.mirror]
| branch l x r ihl ihr =>
simp [Slow.mirror, CPS.mirror, *]
theorem mirror_cps_eq : @CPS.mirror α (BinTree α) id = @Slow.mirror α := by
apply mirror_cps_eq'
-- Exercises
-- ANCHOR: NonTailLength
def NonTail.length : List α → Nat
| [] => 0
| _ :: xs => NonTail.length xs + 1
-- ANCHOR_END: NonTailLength
def Tail.lengthHelper (soFar : Nat) : List α → Nat
| [] => soFar
| _ :: xs => Tail.lengthHelper (soFar + 1) xs
def Tail.length (xs : List α) : Nat :=
Tail.lengthHelper 0 xs
-- ANCHOR: NonTailFact
def NonTail.factorial : Nat → Nat
| 0 => 1
| n + 1 => factorial n * (n + 1)
-- ANCHOR_END: NonTailFact
def Tail.factHelper (soFar : Nat) : Nat → Nat
| 0 => soFar
| n + 1 => factHelper (soFar * (n + 1)) n
def Tail.factorial := factHelper 1
-- ANCHOR: NonTailFilter
def NonTail.filter (p : α → Bool) : List α → List α
| [] => []
| x :: xs =>
if p x then
x :: filter p xs
else
filter p xs
-- ANCHOR_END: NonTailFilter
def Tail.filterHelper (accum : List α) (p : α → Bool) : List α → List α
| [] => accum.reverse
| x :: xs =>
if p x then
filterHelper (x :: accum) p xs
else
filterHelper accum p xs
def Tail.filter (p : α → Bool) := filterHelper [] p
-- ANCHOR: tailFilterTest
example : (
Tail.filter (· > 3) [1,2,3,4,5,6]
) = (
[4,5,6]
) := rfl
-- ANCHOR_END: tailFilterTest
discarding
/-- error:
unsolved goals
xs : List Nat
⊢ ∀ (n : Nat), n + Tail.sum xs = Tail.sumHelper n xs
-/
#check_msgs in
-- ANCHOR: sumEqHelper0
theorem helper_add_sum_accum (xs : List Nat) : (n : Nat) → n + Tail.sum xs = Tail.sumHelper n xs := by
skip
-- ANCHOR_END: sumEqHelper0
stop discarding
discarding
/-- error:
unsolved goals
xs : List Nat
n : Nat
⊢ n + Tail.sum xs = Tail.sumHelper n xs
-/
#check_msgs in
-- ANCHOR: sumEqHelperBad0
theorem helper_add_sum_accum (xs : List Nat) (n : Nat) :
n + Tail.sum xs = Tail.sumHelper n xs := by
skip
-- ANCHOR_END: sumEqHelperBad0
stop discarding
discarding
/-- error:
unsolved goals
case cons
n y : Nat
ys : List Nat
ih : n + Tail.sum ys = Tail.sumHelper n ys
⊢ n + Tail.sum (y :: ys) = Tail.sumHelper n (y :: ys)
-/
#check_msgs in
-- ANCHOR: sumEqHelperBad1
theorem helper_add_sum_accum (xs : List Nat) (n : Nat) :
n + Tail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil => rfl
| cons y ys ih => skip
-- ANCHOR_END: sumEqHelperBad1
stop discarding
discarding
/-- error:
unsolved goals
case cons
n y : Nat
ys : List Nat
ih : n + Tail.sum ys = Tail.sumHelper n ys
⊢ n + Tail.sumHelper y ys = Tail.sumHelper (y + n) ys
-/
#check_msgs in
-- ANCHOR: sumEqHelperBad2
theorem helper_add_sum_accum (xs : List Nat) (n : Nat) :
n + Tail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil => rfl
| cons y ys ih =>
simp [Tail.sum, Tail.sumHelper]
-- ANCHOR_END: sumEqHelperBad2
stop discarding
theorem helper_add_sum_accum (xs : List Nat) :
(n : Nat) → n + Tail.sumHelper 0 xs = Tail.sumHelper n xs := by
induction xs with
| nil => simp [Tail.sumHelper]
| cons y ys ih =>
intro n
simp [Tail.sumHelper]
rw [←ih]
rw [←Nat.add_assoc]
rw [←Nat.add_comm y n]
apply ih
discarding
/-- error:
unsolved goals
⊢ NonTail.sum = Tail.sum
-/
#check_msgs in
-- ANCHOR: sumEq0
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
skip
-- ANCHOR_END: sumEq0
stop discarding
discarding
/-- error:
unsolved goals
case h
xs : List Nat
⊢ NonTail.sum xs = Tail.sum xs
-/
#check_msgs in
-- ANCHOR: sumEq1
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
funext xs
-- ANCHOR_END: sumEq1
stop discarding
discarding
/--
error: unsolved goals
case h.nil
⊢ NonTail.sum [] = Tail.sum []
---
error: unsolved goals
case h.cons
y : Nat
ys : List Nat
ih : NonTail.sum ys = Tail.sum ys
⊢ NonTail.sum (y :: ys) = Tail.sum (y :: ys)
-/
#check_msgs in
-- ANCHOR: sumEq2a
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
funext xs
induction xs with
| nil => skip
| cons y ys ih => skip
-- ANCHOR_END: sumEq2a
stop discarding
discarding
/--
error: unsolved goals
case h.nil
⊢ NonTail.sum [] = Tail.sum []
---
error: unsolved goals
case h.cons
y : Nat
ys : List Nat
ih : NonTail.sum ys = Tail.sum ys
⊢ NonTail.sum (y :: ys) = Tail.sum (y :: ys)
-/
#check_msgs in
-- ANCHOR: sumEq2b
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
funext xs
induction xs with
| nil => skip
| cons y ys ih => skip
-- ANCHOR_END: sumEq2b
stop discarding
discarding
/-- error:
unsolved goals
case h.cons
y : Nat
ys : List Nat
ih : NonTail.sum ys = Tail.sum ys
⊢ NonTail.sum (y :: ys) = Tail.sum (y :: ys)
-/
#check_msgs in
-- ANCHOR: sumEq3
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
funext xs
induction xs with
| nil => rfl
| cons y ys ih => skip
-- ANCHOR_END: sumEq3
stop discarding
discarding
/-- error:
unsolved goals
case h.cons
y : Nat
ys : List Nat
ih : NonTail.sum ys = Tail.sum ys
⊢ y + NonTail.sum ys = Tail.sumHelper 0 (y :: ys)
-/
#check_msgs in
-- ANCHOR: sumEq4
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
funext xs
induction xs with
| nil => rfl
| cons y ys ih =>
simp [NonTail.sum, Tail.sum]
-- ANCHOR_END: sumEq4
stop discarding
discarding
/-- error:
unsolved goals
case h.cons
y : Nat
ys : List Nat
ih : NonTail.sum ys = Tail.sum ys
⊢ y + NonTail.sum ys = Tail.sumHelper y ys
-/
#check_msgs in
-- ANCHOR: sumEq5
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
funext xs
induction xs with
| nil => rfl
| cons y ys ih =>
simp [NonTail.sum, Tail.sum, Tail.sumHelper]
-- ANCHOR_END: sumEq5
stop discarding
discarding
/-- error:
unsolved goals
case h.cons
y : Nat
ys : List Nat
ih : NonTail.sum ys = Tail.sum ys
⊢ y + Tail.sum ys = Tail.sumHelper y ys
-/
#check_msgs in
-- ANCHOR: sumEq6
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
funext xs
induction xs with
| nil => rfl
| cons y ys ih =>
simp [NonTail.sum, Tail.sum, Tail.sumHelper]
rw [ih]
-- ANCHOR_END: sumEq6
stop discarding
discarding
/-- error:
unsolved goals
xs : List Nat
⊢ ∀ (n : Nat), n + NonTail.sum xs = Tail.sumHelper n xs
-/
#check_msgs in
-- ANCHOR: nonTailEqHelper0
theorem non_tail_sum_eq_helper_accum (xs : List Nat) :
(n : Nat) → n + NonTail.sum xs = Tail.sumHelper n xs := by
skip
-- ANCHOR_END: nonTailEqHelper0
stop discarding
discarding
/--
error: unsolved goals
case nil
⊢ ∀ (n : Nat), n + NonTail.sum [] = Tail.sumHelper n []
---
error: unsolved goals
case cons
y : Nat
ys : List Nat
ih : ∀ (n : Nat), n + NonTail.sum ys = Tail.sumHelper n ys
⊢ ∀ (n : Nat), n + NonTail.sum (y :: ys) = Tail.sumHelper n (y :: ys)
-/
#check_msgs in
-- ANCHOR: nonTailEqHelper1a
theorem non_tail_sum_eq_helper_accum (xs : List Nat) :
(n : Nat) → n + NonTail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil => skip
| cons y ys ih => skip
-- ANCHOR_END: nonTailEqHelper1a
stop discarding
discarding
/--
error: unsolved goals
case nil
⊢ ∀ (n : Nat), n + NonTail.sum [] = Tail.sumHelper n []
---
error: unsolved goals
case cons
y : Nat
ys : List Nat
ih : ∀ (n : Nat), n + NonTail.sum ys = Tail.sumHelper n ys
⊢ ∀ (n : Nat), n + NonTail.sum (y :: ys) = Tail.sumHelper n (y :: ys)
-/
#check_msgs in
-- ANCHOR: nonTailEqHelper1b
theorem non_tail_sum_eq_helper_accum (xs : List Nat) :
(n : Nat) → n + NonTail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil => skip
| cons y ys ih => skip
-- ANCHOR_END: nonTailEqHelper1b
stop discarding
discarding
/--
error: unsolved goals
case nil
n : Nat
⊢ n + NonTail.sum [] = Tail.sumHelper n []
---
error: unsolved goals
case cons
y : Nat
ys : List Nat
ih : ∀ (n : Nat), n + NonTail.sum ys = Tail.sumHelper n ys
⊢ ∀ (n : Nat), n + NonTail.sum (y :: ys) = Tail.sumHelper n (y :: ys)
-/
#check_msgs in
-- ANCHOR: nonTailEqHelper2
theorem non_tail_sum_eq_helper_accum (xs : List Nat) :
(n : Nat) → n + NonTail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil => intro n
| cons y ys ih => skip
-- ANCHOR_END: nonTailEqHelper2
stop discarding
discarding
/-- error:
unsolved goals
case cons
y : Nat
ys : List Nat
ih : ∀ (n : Nat), n + NonTail.sum ys = Tail.sumHelper n ys
⊢ ∀ (n : Nat), n + NonTail.sum (y :: ys) = Tail.sumHelper n (y :: ys)
-/
#check_msgs in
-- ANCHOR: nonTailEqHelper3
theorem non_tail_sum_eq_helper_accum (xs : List Nat) :
(n : Nat) → n + NonTail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil =>
intro n
rfl
| cons y ys ih => skip
-- ANCHOR_END: nonTailEqHelper3
stop discarding
discarding
/-- error:
unsolved goals
case cons
y : Nat
ys : List Nat
ih : ∀ (n : Nat), n + NonTail.sum ys = Tail.sumHelper n ys
n : Nat
⊢ n + NonTail.sum (y :: ys) = Tail.sumHelper n (y :: ys)
-/
#check_msgs in
-- ANCHOR: nonTailEqHelper4
theorem non_tail_sum_eq_helper_accum (xs : List Nat) :
(n : Nat) → n + NonTail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil =>
intro n
rfl
| cons y ys ih =>
intro n
-- ANCHOR_END: nonTailEqHelper4
stop discarding
discarding
/-- error:
unsolved goals
case cons
y : Nat
ys : List Nat
ih : ∀ (n : Nat), n + NonTail.sum ys = Tail.sumHelper n ys
n : Nat
⊢ n + (y + NonTail.sum ys) = Tail.sumHelper (y + n) ys
-/
#check_msgs in
-- ANCHOR: nonTailEqHelper5
theorem non_tail_sum_eq_helper_accum (xs : List Nat) :
(n : Nat) → n + NonTail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil =>
intro n
rfl
| cons y ys ih =>
intro n
simp [NonTail.sum, Tail.sumHelper]
-- ANCHOR_END: nonTailEqHelper5
stop discarding
discarding
/-- error:
unsolved goals
case cons
y : Nat
ys : List Nat
ih : ∀ (n : Nat), n + NonTail.sum ys = Tail.sumHelper n ys
n : Nat
⊢ n + y + NonTail.sum ys = Tail.sumHelper (y + n) ys
-/
#check_msgs in
-- ANCHOR: nonTailEqHelper6
theorem non_tail_sum_eq_helper_accum (xs : List Nat) :
(n : Nat) → n + NonTail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil =>
intro n
rfl
| cons y ys ih =>
intro n
simp [NonTail.sum, Tail.sumHelper]
rw [←Nat.add_assoc]
-- ANCHOR_END: nonTailEqHelper6
stop discarding
discarding
/-- error:
unsolved goals
case cons
y : Nat
ys : List Nat
ih : ∀ (n : Nat), n + NonTail.sum ys = Tail.sumHelper n ys
n : Nat
⊢ NonTail.sum ys + (n + y) = Tail.sumHelper (y + n) ys
-/
#check_msgs in
-- ANCHOR: nonTailEqHelper7
theorem non_tail_sum_eq_helper_accum (xs : List Nat) :
(n : Nat) → n + NonTail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil =>
intro n
rfl
| cons y ys ih =>
intro n
simp [NonTail.sum, Tail.sumHelper]
rw [←Nat.add_assoc]
rw [Nat.add_comm]
-- ANCHOR_END: nonTailEqHelper7
stop discarding
discarding
/-- error:
unsolved goals
case cons
y : Nat
ys : List Nat
ih : ∀ (n : Nat), n + NonTail.sum ys = Tail.sumHelper n ys
n : Nat
⊢ n + y + NonTail.sum ys = Tail.sumHelper (n + y) ys
-/
#check_msgs in
-- ANCHOR: nonTailEqHelper8
theorem non_tail_sum_eq_helper_accum (xs : List Nat) :
(n : Nat) → n + NonTail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil =>
intro n
rfl
| cons y ys ih =>
intro n
simp [NonTail.sum, Tail.sumHelper]
rw [←Nat.add_assoc]
rw [Nat.add_comm y n]
-- ANCHOR_END: nonTailEqHelper8
stop discarding
discarding
-- ANCHOR: nonTailEqHelperDone
theorem non_tail_sum_eq_helper_accum (xs : List Nat) :
(n : Nat) → n + NonTail.sum xs = Tail.sumHelper n xs := by
induction xs with
| nil => intro n; rfl
| cons y ys ih =>
intro n
simp [NonTail.sum, Tail.sumHelper]
rw [←Nat.add_assoc]
rw [Nat.add_comm y n]
exact ih (n + y)
-- ANCHOR_END: nonTailEqHelperDone
stop discarding
discarding
/--
error: unsolved goals
case case1
n : Nat
⊢ n + NonTail.sum [] = n
---
error: unsolved goals
case case2
n y : Nat
ys : List Nat
ih : y + n + NonTail.sum ys = Tail.sumHelper (y + n) ys
⊢ n + NonTail.sum (y :: ys) = Tail.sumHelper (y + n) ys
-/
#check_msgs in
-- ANCHOR: nonTailEqHelperFunInd1
theorem non_tail_sum_eq_helper_accum (xs : List Nat) (n : Nat) :
n + NonTail.sum xs = Tail.sumHelper n xs := by
fun_induction Tail.sumHelper with
| case1 n => skip
-- ^ PROOF_STATE: BASE
| case2 n y ys ih => skip
-- ^ PROOF_STATE: STEP
-- ANCHOR_END: nonTailEqHelperFunInd1
stop discarding
discarding
-- ANCHOR: nonTailEqHelperFunInd2
theorem non_tail_sum_eq_helper_accum (xs : List Nat) (n : Nat) :
n + NonTail.sum xs = Tail.sumHelper n xs := by
fun_induction Tail.sumHelper with
| case1 n => simp [NonTail.sum]
| case2 n y ys ih =>
simp [NonTail.sum]
rw [←Nat.add_assoc]
rw [Nat.add_comm n y]
assumption
-- ANCHOR_END: nonTailEqHelperFunInd2
stop discarding
-- ANCHOR: nonTailEqHelperFunInd3
theorem non_tail_sum_eq_helper_accum (xs : List Nat) (n : Nat) :
n + NonTail.sum xs = Tail.sumHelper n xs := by
fun_induction Tail.sumHelper <;> grind [NonTail.sum]
-- ANCHOR_END: nonTailEqHelperFunInd3
-- ANCHOR: NatAddAssoc
example : (n m k : Nat) → (n + m) + k = n + (m + k) := Nat.add_assoc
-- ANCHOR_END: NatAddAssoc
-- ANCHOR: NatAddComm
example : (n m : Nat) → n + m = m + n := Nat.add_comm
-- ANCHOR_END: NatAddComm
discarding
/-- error:
unsolved goals
case h
xs : List Nat
⊢ NonTail.sum xs = Tail.sum xs
-/
#check_msgs in
-- ANCHOR: nonTailEqReal0
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
funext xs
-- ANCHOR_END: nonTailEqReal0
stop discarding
discarding
/-- error:
unsolved goals
case h
xs : List Nat
⊢ NonTail.sum xs = Tail.sumHelper 0 xs
-/
#check_msgs in
-- ANCHOR: nonTailEqReal1
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
funext xs
simp [Tail.sum]
-- ANCHOR_END: nonTailEqReal1
stop discarding
-- ANCHOR: NatZeroAdd
example : (n : Nat) → 0 + n = n := Nat.zero_add
-- ANCHOR_END: NatZeroAdd
namespace Wak
axiom xs : List Nat
-- ANCHOR: NatZeroAddApplied
example : 0 + NonTail.sum xs = NonTail.sum xs := Nat.zero_add (NonTail.sum xs)
-- ANCHOR_END: NatZeroAddApplied
end Wak
discarding
/-- error:
unsolved goals
case h
xs : List Nat
⊢ 0 + NonTail.sum xs = Tail.sumHelper 0 xs
-/
#check_msgs in
-- ANCHOR: nonTailEqReal2
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
funext xs
simp [Tail.sum]
rw [←Nat.zero_add (NonTail.sum xs)]
-- ANCHOR_END: nonTailEqReal2
stop discarding
-- ANCHOR: nonTailEqRealDone
theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
funext xs
simp [Tail.sum]
rw [←Nat.zero_add (NonTail.sum xs)]
exact non_tail_sum_eq_helper_accum xs 0
-- ANCHOR_END: nonTailEqRealDone
theorem reverse_helper (xs : List α) : (ys : List α) → NonTail.reverse xs ++ ys = Tail.reverseHelper ys xs := by
induction xs with
| nil => intro ys; simp [NonTail.reverse, Tail.reverseHelper]
| cons x xs ih =>
intro ys
simp [NonTail.reverse, Tail.reverseHelper, ← ih]
discarding
/-- error:
unsolved goals
case h.h
α : Type u_1
xs : List α
⊢ NonTail.reverse xs = Tail.reverse xs
-/
#check_msgs in
-- ANCHOR: reverseEqStart
theorem non_tail_reverse_eq_tail_reverse :
@NonTail.reverse = @Tail.reverse := by
funext α xs
-- ANCHOR_END: reverseEqStart
stop discarding
theorem non_tail_reverse_eq_tail_reverse :
@NonTail.reverse = @Tail.reverse := by
funext α xs
simp [Tail.reverse]
rw [← List.append_nil (NonTail.reverse xs)]
apply reverse_helper
-- theorem non_tail_sum_eq_tail_sum : NonTail.sum = Tail.sum := by
-- funext xs
-- induction xs with
-- | nil => rfl
-- | cons y ys ih =>
-- simp [NonTail.sum, Tail.sum, Tail.sumHelper]
-- rw [ih]
-- apply helper_simulates_non_tail
def bigList (n : Nat) (soFar : List Nat) : List Nat :=
match n with
| 0 => soFar
| k + 1 =>
bigList k (2 * n :: soFar)
-- #eval timeit "hello" (IO.println theBigList.length)
-- #eval timeit "a" (IO.println <| Tail.sum theBigList)
-- #eval timeit "b" (IO.println <| NonTail.sum theBigList)
-- ANCHOR: names
section
example := @List.cons
end
-- ANCHOR_END: names
-- ANCHOR: accum_stmt
section
variable {n}
example := Tail.sumHelper n
end
section
variable {ys : List α}
example := Tail.reverseHelper ys
example := Tail.reverseHelper [] ys
end
-- ANCHOR_END: accum_stmt |
fp-lean/examples/Examples/ProgramsProofs/Arrays.lean | import ExampleSupport
namespace Orders
-- ANCHOR: less
class LE (α : Type u) where
le : α → α → Prop
class LT (α : Type u) where
lt : α → α → Prop
-- ANCHOR_END: less
attribute [inherit_doc _root_.LE] LE
attribute [inherit_doc _root_.LE.le] LE.le
attribute [inherit_doc _root_.LT] LT
attribute [inherit_doc _root_.LT.lt] LT.lt
-- ANCHOR: NatLe
inductive Nat.le (n : Nat) : Nat → Prop
| refl : Nat.le n n
| step : Nat.le n m → Nat.le n (m + 1)
-- ANCHOR_END: NatLe
attribute [inherit_doc _root_.Nat.le] Nat.le
attribute [inherit_doc _root_.Nat.le.refl] Nat.le.refl
attribute [inherit_doc _root_.Nat.le.step] Nat.le.step
-- ANCHOR: leNames
example := @Nat.le.refl
example := @Nat.le.step
-- ANCHOR_END: leNames
--ANCHOR: ForMArr
example {α m} := ForM m (Array α)
--ANCHOR_END: ForMArr
-- ANCHOR: LENat
instance : LE Nat where
le := Nat.le
-- ANCHOR_END: LENat
-- ANCHOR: NatLt
def Nat.lt (n m : Nat) : Prop :=
Nat.le (n + 1) m
instance : LT Nat where
lt := Nat.lt
-- ANCHOR_END: NatLt
end Orders
example := Nat.le
-- ANCHOR: EasyToProve
inductive EasyToProve : Prop where
| heresTheProof : EasyToProve
-- ANCHOR_END: EasyToProve
-- ANCHOR: fairlyEasy
theorem fairlyEasy : EasyToProve := by
constructor
-- ANCHOR_END: fairlyEasy
namespace Argh
-- ANCHOR: True
inductive True : Prop where
| intro : True
-- ANCHOR_END: True
end Argh
-- ANCHOR: IsThree
inductive IsThree : Nat → Prop where
| isThree : IsThree 3
-- ANCHOR_END: IsThree
-- ANCHOR: IsFive
inductive IsFive : Nat → Prop where
| isFive : IsFive 5
-- ANCHOR_END: IsFive
-- ANCHOR: threeIsThree
theorem three_is_three : IsThree 3 := by
constructor
-- ANCHOR_END: threeIsThree
discarding
/-- error:
unsolved goals
n : Nat
⊢ IsThree n → IsFive (n + 2)
-/
#check_msgs in
-- ANCHOR: threePlusTwoFive0
theorem three_plus_two_five : IsThree n → IsFive (n + 2) := by
skip
-- ANCHOR_END: threePlusTwoFive0
stop discarding
-- ANCHOR: various
example := 3 + 2
example := False
example {A} := [(Not A), (A → False), ¬ A]
-- ANCHOR_END: various
discarding
/-- error:
unsolved goals
n : Nat
three : IsThree n
⊢ IsFive (n + 2)
-/
#check_msgs in
-- ANCHOR: threePlusTwoFive1
theorem three_plus_two_five : IsThree n → IsFive (n + 2) := by
intro three
-- ANCHOR_END: threePlusTwoFive1
stop discarding
discarding
/--
error: Tactic `constructor` failed: no applicable constructor found
n : Nat
three : IsThree n
⊢ IsFive (n + 2)
-/
#check_msgs in
-- ANCHOR: threePlusTwoFive1a
theorem three_plus_two_five : IsThree n → IsFive (n + 2) := by
intro three
constructor
-- ANCHOR_END: threePlusTwoFive1a
stop discarding
discarding
/-- error:
unsolved goals
case isThree
⊢ IsFive (3 + 2)
-/
#check_msgs in
-- ANCHOR: threePlusTwoFive2
theorem three_plus_two_five : IsThree n → IsFive (n + 2) := by
intro three
cases three with
| isThree => skip
-- ANCHOR_END: threePlusTwoFive2
stop discarding
discarding
-- ANCHOR: threePlusTwoFive3
theorem three_plus_two_five : IsThree n → IsFive (n + 2) := by
intro three
cases three with
| isThree => constructor
-- ANCHOR_END: threePlusTwoFive3
stop discarding
discarding
/-- error:
unsolved goals
⊢ ¬IsThree 4
-/
#check_msgs in
-- ANCHOR: fourNotThree0
theorem four_is_not_three : ¬ IsThree 4 := by
skip
-- ANCHOR_END: fourNotThree0
stop discarding
discarding
/-- error:
unsolved goals
⊢ IsThree 4 → False
-/
#check_msgs in
-- ANCHOR: fourNotThree1
theorem four_is_not_three : ¬ IsThree 4 := by
unfold Not
-- ANCHOR_END: fourNotThree1
stop discarding
discarding
/-- error:
unsolved goals
h : IsThree 4
⊢ False
-/
#check_msgs in
-- ANCHOR: fourNotThree2
theorem four_is_not_three : ¬ IsThree 4 := by
intro h
-- ANCHOR_END: fourNotThree2
stop discarding
discarding
-- ANCHOR: fourNotThreeDone
theorem four_is_not_three : ¬ IsThree 4 := by
intro h
cases h
-- ANCHOR_END: fourNotThreeDone
stop discarding
-- ANCHOR: four_le_seven
theorem four_le_seven : 4 ≤ 7 :=
open Nat.le in
step (step (step refl))
-- ANCHOR_END: four_le_seven
-- ANCHOR: four_lt_seven
theorem four_lt_seven : 4 < 7 :=
open Nat.le in
step (step refl)
-- ANCHOR_END: four_lt_seven
-- ANCHOR: four_lt_seven_alt
example : (4 < 7) = (5 ≤ 7) := rfl
-- ANCHOR_END: four_lt_seven_alt
namespace WithFor
def Array.map (f : α → β) (arr : Array α) : Array β := Id.run do
let mut out : Array β := Array.empty
for x in arr do
out := out.push (f x)
pure out
end WithFor
discarding
/-- error:
failed to prove index is valid, possible solutions:
- Use `have`-expressions to prove the index is valid
- Use `a[i]!` notation instead, runtime check is performed, and 'Panic' error message is produced if index is not valid
- Use `a[i]?` notation instead, result is an `Option` type
- Use `a[i]'h` notation instead, where `h` is a proof that index is valid
α : Type ?u.1290
β : Type ?u.1293
f : α → β
arr : Array α
soFar : Array β
i : Nat
⊢ i < arr.size
-/
#check_msgs in
-- ANCHOR: mapHelperIndexIssue
def arrayMapHelper (f : α → β) (arr : Array α)
(soFar : Array β) (i : Nat) : Array β :=
if i < arr.size then
arrayMapHelper f arr (soFar.push (f arr[i])) (i + 1)
else soFar
-- ANCHOR_END: mapHelperIndexIssue
stop discarding
discarding
-- ANCHOR: arrayMapHelperTermIssue
def arrayMapHelper (f : α → β) (arr : Array α)
(soFar : Array β) (i : Nat) : Array β :=
if inBounds : i < arr.size then
arrayMapHelper f arr (soFar.push (f arr[i])) (i + 1)
else soFar
-- ANCHOR_END: arrayMapHelperTermIssue
stop discarding
-- ANCHOR: ArrayMapHelperOk
def arrayMapHelper (f : α → β) (arr : Array α)
(soFar : Array β) (i : Nat) : Array β :=
if inBounds : i < arr.size then
arrayMapHelper f arr (soFar.push (f arr[i])) (i + 1)
else soFar
termination_by arr.size - i
-- ANCHOR_END: ArrayMapHelperOk
namespace TailRec
-- ANCHOR: ArrayMap
def Array.map (f : α → β) (arr : Array α) : Array β :=
arrayMapHelper f arr Array.empty 0
-- ANCHOR_END: ArrayMap
end TailRec
-- ANCHOR: ArrayFindHelper
def findHelper (arr : Array α) (p : α → Bool)
(i : Nat) : Option (Nat × α) :=
if h : i < arr.size then
let x := arr[i]
if p x then
some (i, x)
else findHelper arr p (i + 1)
else none
-- ANCHOR_END: ArrayFindHelper
-- ANCHOR: ArrayFind
def Array.find (arr : Array α) (p : α → Bool) :
Option (Nat × α) :=
findHelper arr p 0
-- ANCHOR_END: ArrayFind
namespace Huh
/--
info: Try this:
[apply] termination_by arr.size - i
-/
#check_msgs in
-- ANCHOR: ArrayFindHelperSugg
def findHelper (arr : Array α) (p : α → Bool)
(i : Nat) : Option (Nat × α) :=
if h : i < arr.size then
let x := arr[i]
if p x then
some (i, x)
else findHelper arr p (i + 1)
else none
termination_by?
-- ANCHOR_END: ArrayFindHelperSugg
end Huh |
fp-lean/examples/feline/1/Main.lean | def main : IO Unit :=
IO.println s!"Hello, cats!" |
fp-lean/examples/feline/2/test1.txt | It's time to find a warm spot |
fp-lean/examples/feline/2/test2.txt | and curl up! |
fp-lean/examples/feline/2/FelineLib.lean | -- ANCHOR: bufsize
def bufsize : USize := 20 * 1024
-- ANCHOR_END: bufsize
-- ANCHOR: dump
partial def dump (stream : IO.FS.Stream) : IO Unit := do
let buf ← stream.read bufsize
if buf.isEmpty then
pure ()
else
-- ANCHOR: stdoutBind
let stdout ← IO.getStdout
stdout.write buf
-- ANCHOR_END: stdoutBind
dump stream
-- ANCHOR_END: dump
-- ANCHOR: fileStream
def fileStream (filename : System.FilePath) : IO (Option IO.FS.Stream) := do
-- ANCHOR: fileExistsBind
let fileExists ← filename.pathExists
if not fileExists then
-- ANCHOR_END: fileExistsBind
let stderr ← IO.getStderr
stderr.putStrLn s!"File not found: {filename}"
pure none
else
let handle ← IO.FS.Handle.mk filename IO.FS.Mode.read
pure (some (IO.FS.Stream.ofHandle handle))
-- ANCHOR_END: fileStream
-- ANCHOR: Names
section
open IO.FS
#check Stream
open System
#check FilePath
namespace Main1
def main : IO Unit := pure ()
end Main1
namespace Main2
def main : IO UInt32 := pure 0
end Main2
namespace Main3
def main : List String → IO UInt32 := fun _ => pure 0
end Main3
end
-- ANCHOR_END: Names
-- ANCHOR: process
def process (exitCode : UInt32) (args : List String) : IO UInt32 := do
match args with
| [] => pure exitCode
| "-" :: args =>
let stdin ← IO.getStdin
dump stdin
process exitCode args
| filename :: args =>
let stream ← fileStream ⟨filename⟩
match stream with
| none =>
process 1 args
| some stream =>
dump stream
process exitCode args
-- ANCHOR_END: process
-- ANCHOR: main
def main (args : List String) : IO UInt32 :=
match args with
| [] => process 0 ["-"]
| _ => process 0 args
-- ANCHOR_END: main
example := USize |
fp-lean/examples/feline/2/Main.lean | import FelineLib |
fp-lean/examples/feline/2/expected/test12.txt | It's time to find a warm spot
and curl up! |
fp-lean/examples/feline/2/expected/test1purr2.txt | It's time to find a warm spot
and purr
and curl up! |
fp-lean/examples/hello-name/HelloName.lean | -- ANCHOR: all
-- ANCHOR: sig
def main : IO Unit := do
-- ANCHOR_END: sig
-- ANCHOR: setup
let stdin ← IO.getStdin
let stdout ← IO.getStdout
-- ANCHOR_END: setup
-- ANCHOR: question
stdout.putStrLn "How would you like to be addressed?"
let input ← stdin.getLine
let name := input.dropRightWhile Char.isWhitespace
-- ANCHOR_END: question
-- ANCHOR: answer
stdout.putStrLn s!"Hello, {name}!"
-- ANCHOR_END: answer
-- ANCHOR_END: all
def mainSplit : IO Unit := do
-- ANCHOR: block1
-- ANCHOR: line1
let stdin ← IO.getStdin
-- ANCHOR_END: line1
-- ANCHOR: block2
-- ANCHOR: line2
let stdout ← IO.getStdout
-- ANCHOR_END: line2
-- ANCHOR: block3
-- ANCHOR: line3
stdout.putStrLn "How would you like to be addressed?"
-- ANCHOR_END: line3
-- ANCHOR: block4
-- ANCHOR: line4
let input ← stdin.getLine
-- ANCHOR_END: line4
-- ANCHOR: block5
-- ANCHOR: line5
let name := input.dropRightWhile Char.isWhitespace
-- ANCHOR_END: line5
-- ANCHOR: block6
-- ANCHOR: line6
stdout.putStrLn s!"Hello, {name}!"
-- ANCHOR_END: line6
-- ANCHOR_END: block6
-- ANCHOR_END: block5
-- ANCHOR_END: block4
-- ANCHOR_END: block3
-- ANCHOR_END: block2
-- ANCHOR_END: block1
-- Keep checking that they're identical
example : main = mainSplit := by rfl
example := String.dropRightWhile
example {α : Type} := IO α
example : String → IO Unit := IO.println
example := Bool
open Unit in
example : Unit := unit
example := IO.FS.Stream
example : IO.FS.Stream → String → IO Unit := IO.FS.Stream.putStrLn
example : IO.FS.Stream → IO String := IO.FS.Stream.getLine |
fp-lean/.github/ISSUE_TEMPLATE/technical-error.md | ---
name: Technical error
about: Descriptions of technical mistakes in the content of the book
title: ''
labels: ''
assignees: ''
---
Please quote the text that is incorrect:
> MISTAKE GOES HERE
In what way is this incorrect? |
fp-lean/.github/ISSUE_TEMPLATE/typo.md | ---
name: Typo
about: Point out a typographical or grammatical error in the text
title: "[Typo] "
labels: Typo
assignees: ''
---
Please quote the complete incorrect sentence - this makes it easy to find in the source code of the book.
Thank you! |
fp-lean/book/README.md | # book |
fp-lean/book/FPLean.lean | import VersoManual
import FPLean.Intro
import FPLean.Acks
import FPLean.GettingToKnow
import FPLean.HelloWorld
import FPLean.PropsProofsIndexing
import FPLean.TypeClasses
import FPLean.Monads
import FPLean.FunctorApplicativeMonad
import FPLean.MonadTransformers
import FPLean.DependentTypes
import FPLean.TacticsInductionProofs
import FPLean.ProgramsProofs
import FPLean.NextSteps
open Verso.Genre Manual
open Verso Code External
open Verso Doc Elab in
open Lean (quote) in
@[role_expander versionString]
def versionString : RoleExpander
| #[], #[] => do
let version ← IO.FS.readFile "../examples/lean-toolchain"
let version := version.stripPrefix "leanprover/lean4:" |>.trim
pure #[← ``(Verso.Doc.Inline.code $(quote version))]
| _, _ => throwError "Unexpected arguments"
#doc (Manual) "Functional Programming in Lean" =>
%%%
authors := ["David Thrane Christiansen"]
%%%
_Copyright Microsoft Corporation 2023 and Lean FRO, LLC 2023–2025_
This is a free book on using Lean as a programming language. All code samples are tested with Lean release {versionString}[].
{include 1 FPLean.Intro}
{include 1 FPLean.Acks}
{include 1 FPLean.GettingToKnow}
{include 1 FPLean.HelloWorld}
{include 1 FPLean.PropsProofsIndexing}
{include 1 FPLean.TypeClasses}
{include 1 FPLean.Monads}
{include 1 FPLean.FunctorApplicativeMonad}
{include 1 FPLean.MonadTransformers}
{include 1 FPLean.DependentTypes}
{include 1 FPLean.TacticsInductionProofs}
{include 1 FPLean.ProgramsProofs}
{include 1 FPLean.NextSteps} |
fp-lean/book/lakefile.lean | import Lake
open System Lake DSL
package book where
version := v!"0.1.0"
leanOptions :=
#[⟨`weak.verso.examples.suggest, true⟩,
⟨`weak.linter.verso.manual.headerTags, true⟩,
⟨`weak.verso.externalExamples.suppressedNamespaces,
"A Adding Agh Argh Almost Alt AltPos AndDef AndThen AppendOverloads ApplicativeOptionLaws ApplicativeOptionLaws2 ApplicativeToFunctor Apply Argh AutoImpl B BadUnzip BetterHPlus BetterPlicity Blurble Both Busted C CheckFunctorPair Class Cls Cmp Connectives Cont Ctor D Decide Demo Desugared Details DirTree DirTree.Old DirTree.Readerish DirTree.T Double EEE EarlyReturn Eff Errs Eta Evaluator Even Ex Exercises Explicit ExplicitParens Extra Extras F F1 F2 Fake FakeAlternative FakeCoe FakeExcept FakeFunctor FakeMonad FakeOrElse FakeSeqRight FancyDo FastPos FinDef Finny Fixity Floop ForMIO Foo Foo2 Four FourPointFive Golf Golf' Guard H HelloName1 HelloName2 HelloName3 Huh IdentMonad Impl Improved Inductive Inflexible IterSub L Lawful ListExtras Loops Loops.Cont M MMM Main1 Main2 Main3 Match MatchDef Mine Modify MonadApplicative MonadApplicativeDesugar MonadApplicativeProof1 MonadApplicativeProof2 MonadApplicativeProof3 MonadApplicativeProof4 MonadLaws Monadicish Monads.Err Monads.Option Monads.State Monads.Writer More MoreClear MoreMonadic Mut MyList1 MyList15 MyList3 MyListStuff MyMonadExcept MyMonadLift MySum NRT NT NatLits Nested New NoTac Non Numbering Numbering.Short Old One OneAttempt Oooops Ooops Oops Opt Option OrElse Orders Original Other OverloadedBits OverloadedInt OwnInstances Partial PipelineEx PointStuff ProblematicHPlus Prod Proofs PropStuff Provisional Provisional2 R Ranges Readerish ReallyNoTypes Reorder SameDo SeqCounterexample SeqLeftSugar SeqRightSugar Ser Short St StEx StdLibNoUni Str StructNotation Structed SubtypeDemo SugaryOrElse Sum T TTT Tactical TailRec Temp ThenDoUnless Three Transformed Two U Up UseList VariousTypes Verbose Wak Whatevs WithAndThen WithDo WithFor WithInfix WithMatch WithPattern"⟩]
require verso from git "https://github.com/leanprover/verso.git"@"main"
private def examplePath : System.FilePath := "../examples"
private def lakeVars :=
#["LAKE", "LAKE_HOME", "LAKE_PKG_URL_MAP", "LAKE_CACHE_DIR",
"LEAN", "LEAN_SYSROOT", "LEAN_AR", "LEAN_PATH", "LEAN_SRC_PATH",
"LEAN_GITHASH",
"ELAN_TOOLCHAIN", "DYLD_LIBRARY_PATH", "LD_LIBRARY_PATH"]
private def fixPath (path : System.SearchPath) : String :=
path |>.map (·.toString) |>.filter (!·.contains ".lake") |> System.SearchPath.separator.toString.intercalate
input_dir examples where
path := examplePath
text := true
filter := .extension "lean"
input_dir exampleBinaries where
path := examplePath / ".lake" / "build" / "bin"
text := false
target buildExamples (pkg) : Unit := do
let exs ← examples.fetch
let exBins ← exampleBinaries.fetch
let toolchainFile := examplePath / "lean-toolchain"
let toolchain ← IO.FS.readFile toolchainFile
let toolchain := toolchain.trimAscii |>.dropPrefix "leanprover/lean4:" |>.dropPrefix "v" |>.copy
addPureTrace toolchain
exBins.bindM fun binFiles => do
for file in binFiles do
if file.extension.isNone || file.extension.isEqSome System.FilePath.exeExtension then
addTrace (← computeTrace file)
exs.mapM fun exFiles => do
let mut list := ""
for file in exFiles do
addTrace (← computeTrace <| TextFilePath.mk file)
list := list ++ s!"{file}\n"
buildFileUnlessUpToDate' (pkg.buildDir / "examples-built") (text := true) do
Lake.logInfo s!"Building examples in {examplePath}"
let mut out := ""
let path := fixPath (← getSearchPath "PATH")
out := out ++ (← captureProc {
cmd := "elan",
args := #["run", "--install", toolchain, "lake", "build"],
cwd := examplePath,
env := lakeVars.map (·, none) ++ #[("PATH", some path)]
})
out := out ++ (← captureProc {
cmd := "elan",
args := #["run", "--install", toolchain, "lake", "build", "subverso-extract-mod"],
cwd := examplePath,
env := lakeVars.map (·, none) ++ #[("PATH", some path)]
})
IO.FS.createDirAll pkg.buildDir
IO.FS.writeFile (pkg.buildDir / "examples-built") (list ++ "--- Output ---\n" ++ out)
target syncBuildExamples : Unit := do
.pure <$> (← buildExamples.fetch).await
lean_lib FPLean where
needs := #[syncBuildExamples]
@[default_target] lean_exe «fp-lean» where root := `Main |
fp-lean/book/Main.lean | import VersoManual
import FPLean
open Verso.Genre Manual
open Verso Code External
open Verso.Output.Html in
def plausible := {{
<script defer="defer" data-domain="lean-lang.org" src="https://plausible.io/js/script.outbound-links.js"></script>
}}
def config : Config where
emitTeX := false
emitHtmlSingle := false
emitHtmlMulti := true
htmlDepth := 2
extraFiles := [("static", "static")]
extraCss := [
"/static/theme.css",
"/static/fonts/source-serif/source-serif-text.css",
"/static/fonts/source-code-pro/source-code-pro.css",
"/static/fonts/source-sans/source-sans-3.css",
"/static/fonts/noto-sans-mono/noto-sans-mono.css"
]
extraHead := #[plausible]
logo := some "/static/lean_logo.svg"
sourceLink := some "https://github.com/leanprover/fp-lean"
issueLink := some "https://github.com/leanprover/fp-lean/issues"
linkTargets := fun st => st.localTargets ++ st.remoteTargets
def main := manualMain (%doc FPLean) (config := config.addKaTeX) |
fp-lean/book/FPLean/Intro.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.Intro"
#doc (Manual) "Introduction" =>
%%%
htmlSplit := .never
number := false
%%%
Lean is an interactive theorem prover based on dependent type theory.
Originally developed at Microsoft Research, development now takes place at the [Lean FRO](https://lean-fro.org).
Dependent type theory unites the worlds of programs and proofs; thus, Lean is also a programming language.
Lean takes its dual nature seriously, and it is designed to be suitable for use as a general-purpose programming language—Lean is even implemented in itself.
This book is about writing programs in Lean.
When viewed as a programming language, Lean is a strict pure functional language with dependent types.
A large part of learning to program with Lean consists of learning how each of these attributes affects the way programs are written, and how to think like a functional programmer.
_Strictness_ means that function calls in Lean work similarly to the way they do in most languages: the arguments are fully computed before the function's body begins running.
_Purity_ means that Lean programs cannot have side effects such as modifying locations in memory, sending emails, or deleting files without the program's type saying so.
Lean is a _functional_ language in the sense that functions are first-class values like any other and that the execution model is inspired by the evaluation of mathematical expressions.
_Dependent types_, which are the most unusual feature of Lean, make types into a first-class part of the language, allowing types to contain programs and programs to compute types.
This book is intended for programmers who want to learn Lean, but who have not necessarily used a functional programming language before.
Familiarity with functional languages such as Haskell, OCaml, or F# is not required.
On the other hand, this book does assume knowledge of concepts like loops, functions, and data structures that are common to most programming languages.
While this book is intended to be a good first book on functional programming, it is not a good first book on programming in general.
Mathematicians who are using Lean as a proof assistant will likely need to write custom proof automation tools at some point.
This book is also for them.
As these tools become more sophisticated, they begin to resemble programs in functional languages, but most working mathematicians are trained in languages like Python and Mathematica.
This book can help bridge the gap, empowering more mathematicians to write maintainable and understandable proof automation tools.
This book is intended to be read linearly, from the beginning to the end.
Concepts are introduced one at a time, and later sections assume familiarity with earlier sections.
Sometimes, later chapters will go into depth on a topic that was only briefly addressed earlier on.
Some sections of the book contain exercises.
These are worth doing, in order to cement your understanding of the section.
It is also useful to explore Lean as you read the book, finding creative new ways to use what you have learned.
# Getting Lean
%%%
tag := "getting-lean"
%%%
Before writing and running programs written in Lean, you'll need to set up Lean on your own computer.
The Lean tooling consists of the following:
* {lit}`elan` manages the Lean compiler toolchains, similarly to {lit}`rustup` or {lit}`ghcup`.
* {lit}`lake` builds Lean packages and their dependencies, similarly to {lit}`cargo`, {lit}`make`, or Gradle.
* {lit}`lean` type checks and compiles individual Lean files as well as providing information to programmer tools about files that are currently being written.
Normally, {lit}`lean` is invoked by other tools rather than directly by users.
* Plugins for editors, such as Visual Studio Code or Emacs, that communicate with {lit}`lean` and present its information conveniently.
Please refer to the [Lean manual](https://lean-lang.org/lean4/doc/quickstart.html) for up-to-date instructions for installing Lean.
# Typographical Conventions
%%%
tag := "typographical-conventions"
%%%
Code examples that are provided to Lean as _input_ are formatted like this:
```anchor add1
def add1 (n : Nat) : Nat := n + 1
```
```anchorTerm add1_7
#eval add1 7
```
The last line above (beginning with {kw}`#eval`) is a command that instructs Lean to calculate an answer.
Lean's replies are formatted like this:
```anchorInfo add1_7
8
```
Error messages returned by Lean are formatted like this:
```anchorError add1_string
Application type mismatch: The argument
"seven"
has type
String
but is expected to have type
Nat
in the application
add1 "seven"
```
Warnings are formatted like this:
```anchorWarning add1_warn
declaration uses 'sorry'
```
# Unicode
%%%
tag := "unicode"
%%%
Idiomatic Lean code makes use of a variety of Unicode characters that are not part of ASCII.
For instance, Greek letters like {lit}`α` and {lit}`β` and the arrow {lit}`→` both occur in the first chapter of this book.
This allows Lean code to more closely resemble ordinary mathematical notation.
With the default Lean settings, both Visual Studio Code and Emacs allow these characters to be typed with a backslash ({lit}`\`) followed by a name.
For example, to enter {lit}`α`, type {lit}`\alpha`.
To find out how to type a character in Visual Studio Code, point the mouse at it and look at the tooltip.
In Emacs, use {lit}`C-c C-k` with point on the character in question.
# Release history
%%%
tag := "release-history"
number := false
htmlSplit := .never
%%%
## October, 2025
%%%
tag := none
%%%
The book has been updated to the latest stable Lean release (version 4.23.0), and now describes functional induction and the {tactic}`grind` tactic.
## August, 2025
%%%
tag := none
%%%
This is a maintenance release to resolve an issue with copy-pasting code from the book.
## July, 2025
%%%
tag := none
%%%
The book has been updated for version 4.21 of Lean.
## June, 2025
%%%
tag := none
%%%
The book has been reformatted with Verso.
## April, 2025
%%%
tag := none
%%%
The book has been extensively updated and now describes Lean version 4.18.
## January, 2024
%%%
tag := none
%%%
This is a minor bugfix release that fixes a regression in an example program.
## October, 2023
%%%
tag := none
%%%
In this first maintenance release, a number of smaller issues were fixed and the text was brought up to date with the latest release of Lean.
## May, 2023
%%%
tag := none
%%%
The book is now complete! Compared to the April pre-release, many small details have been improved and minor mistakes have been fixed.
## April, 2023
%%%
tag := none
%%%
This release adds an interlude on writing proofs with tactics as well as a final chapter that combines discussion of performance and cost models with proofs of termination and program equivalence.
This is the last release prior to the final release.
## March, 2023
%%%
tag := none
%%%
This release adds a chapter on programming with dependent types and indexed families.
## January, 2023
%%%
tag := none
%%%
This release adds a chapter on monad transformers that includes a description of the imperative features that are available in {kw}`do`-notation.
## December, 2022
%%%
tag := none
%%%
This release adds a chapter on applicative functors that additionally describes structures and type classes in more detail.
This is accompanied with improvements to the description of monads.
The December 2022 release was delayed until January 2023 due to winter holidays.
## November, 2022
%%%
tag := none
%%%
This release adds a chapter on programming with monads. Additionally, the example of using JSON in the coercions section has been updated to include the complete code.
## October, 2022
%%%
tag := none
%%%
This release completes the chapter on type classes. In addition, a short interlude introducing propositions, proofs, and tactics has been added just before the chapter on type classes, because a small amount of familiarity with the concepts helps to understand some of the standard library type classes.
## September, 2022
%%%
tag := none
%%%
This release adds the first half of a chapter on type classes, which are Lean's mechanism for overloading operators and an important means of organizing code and structuring libraries. Additionally, the second chapter has been updated to account for changes in Lean's stream API.
## August, 2022
%%%
tag := none
%%%
This third public release adds a second chapter, which describes compiling and running programs along with Lean's model for side effects.
## July, 2022
%%%
tag := none
%%%
The second public release completes the first chapter.
## June, 2022
%%%
tag := none
%%%
This was the first public release, consisting of an introduction and part of the first chapter.
# About the Author
%%%
tag := "about-the-author"
%%%
David Thrane Christiansen has been using functional languages for twenty years, and dependent types for ten.
Together with Daniel P. Friedman, he wrote [_The Little Typer_](https://thelittletyper.com/), an introduction to the key ideas of dependent type theory.
He has a Ph.D. from the IT University of Copenhagen.
During his studies, he was a major contributor to the first version of the Idris language.
Since leaving academia, he has worked as a software developer at Galois in Portland, Oregon and Deon Digital in Copenhagen, Denmark, and he was the Executive Director of the Haskell Foundation.
At the time of writing, he is employed at the [Lean Focused Research Organization](https://lean-fro.org) working full-time on Lean.
# License
%%%
tag := "license"
%%%
{creativeCommons}
The original version of the book was written by David Thrane Christiansen on contract to Microsoft Corporation, who generously released it under a Creative Commons Attribution 4.0 International License.
The current version has been modified by the author from the original version to account for changes in newer versions of Lean.
A detailed account of the changes can be found in the book's [source code repository](https://github.com/leanprover/fp-lean/). |
fp-lean/book/FPLean/TacticsInductionProofs.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.Induction"
#doc (Manual) "Interlude: Tactics, Induction, and Proofs" =>
%%%
tag := "tactics-induction-proofs"
number := false
htmlSplit := .never
%%%
# A Note on Proofs and User Interfaces
%%%
tag := "proofs-and-uis"
%%%
This book presents the process of writing proofs as if they are written in one go and submitted to Lean, which then replies with error messages that describe what remains to be done.
The actual process of interacting with Lean is much more pleasant.
Lean provides information about the proof as the cursor is moved through it and there are a number of interactive features that make proving easier.
Please consult the documentation of your Lean development environment for more information.
The approach in this book that focuses on incrementally building a proof and showing the messages that result demonstrates the kinds of interactive feedback that Lean provides while writing a proof, even though it is much slower than the process used by experts.
At the same time, seeing incomplete proofs evolve towards completeness is a useful perspective on proving.
As your skill in writing proofs increases, Lean's feedback will come to feel less like errors and more like support for your own thought processes.
Learning the interactive approach is very important.
# Recursion and Induction
%%%
tag := "recursion-vs-induction"
%%%
The functions {anchorName plusR_succ_left (module := Examples.DependentTypes.Pitfalls)}`plusR_succ_left` and {anchorName plusR_zero_left_thm (module:=Examples.DependentTypes.Pitfalls)}`plusR_zero_left` from the preceding chapter can be seen from two perspectives.
On the one hand, they are recursive functions that build up evidence for a proposition, just as other recursive functions might construct a list, a string, or any other data structure.
On the other, they also correspond to proofs by _mathematical induction_.
Mathematical induction is a proof technique where a statement is proven for _all_ natural numbers in two steps:
1. The statement is shown to hold for $`0`. This is called the _base case_.
2. Under the assumption that the statement holds for some arbitrarily chosen number $`n`, it is shown to hold for $`n + 1`. This is called the _induction step_. The assumption that the statement holds for $`n` is called the _induction hypothesis_.
Because it's impossible to check the statement for _every_ natural number, induction provides a means of writing a proof that could, in principle, be expanded to any particular natural number.
For example, if a concrete proof were desired for the number 3, then it could be constructed by using first the base case and then the induction step three times, to show the statement for 0, 1, 2, and finally 3.
Thus, it proves the statement for all natural numbers.
# The Induction Tactic
%%%
tag := "induction-tactic"
%%%
Writing proofs by induction as recursive functions that use helpers such as {anchorName plusR_zero_left_done (module:=Examples.DependentTypes.Pitfalls)}`congrArg` does not always do a good job of expressing the intentions behind the proof.
While recursive functions indeed have the structure of induction, they should probably be viewed as an _encoding_ of a proof.
Furthermore, Lean's tactic system provides a number of opportunities to automate the construction of a proof that are not available when writing the recursive function explicitly.
Lean provides an induction _tactic_ that can carry out an entire proof by induction in a single tactic block.
Behind the scenes, Lean constructs the recursive function that corresponds the use of induction.
To prove {anchorName plusR_zero_left_done (module:=Examples.DependentTypes.Pitfalls)}`plusR_zero_left` with the {kw}`induction` tactic, begin by writing its signature (using {kw}`theorem`, because this really is a proof).
Then, use {anchorTerm plusR_ind_zero_left_1}`by induction k` as the body of the definition:
```anchor plusR_ind_zero_left_1
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k
```
The resulting message states that there are two goals:
```anchorError plusR_ind_zero_left_1
unsolved goals
case zero
⊢ 0 = Nat.plusR 0 0
case succ
n✝ : Nat
a✝ : n✝ = Nat.plusR 0 n✝
⊢ n✝ + 1 = Nat.plusR 0 (n✝ + 1)
```
A tactic block is a program that is run while the Lean type checker processes a file, somewhat like a much more powerful C preprocessor macro.
The tactics generate the actual program.
In the tactic language, there can be a number of goals.
Each goal consists of a type together with some assumptions.
These are analogous to using underscores as placeholders—the type in the goal represents what is to be proved, and the assumptions represent what is in-scope and can be used.
In the case of the goal {lit}`case zero`, there are no assumptions and the type is {anchorTerm others}`Nat.zero = Nat.plusR 0 Nat.zero`—this is the theorem statement with {anchorTerm others}`0` instead of {anchorName plusR_ind_zero_left_1}`k`.
In the goal {lit}`case succ`, there are two assumptions, named {lit}`n✝` and {lit}`n_ih✝`.
Behind the scenes, the {anchorTerm plusR_ind_zero_left_1}`induction` tactic creates a dependent pattern match that refines the overall type, and {lit}`n✝` represents the argument to {anchorName others}`Nat.succ` in the pattern.
The assumption {lit}`n_ih✝` represents the result of calling the generated function recursively on {lit}`n✝`.
Its type is the overall type of the theorem, just with {lit}`n✝` instead of {anchorName plusR_ind_zero_left_1}`k`.
The type to be fulfilled as part of the goal {lit}`case succ` is the overall theorem statement, with {lit}`Nat.succ n✝` instead of {anchorName plusR_ind_zero_left_1}`k`.
The two goals that result from the use of the {anchorTerm plusR_ind_zero_left_1}`induction` tactic correspond to the base case and the induction step in the description of mathematical induction.
The base case is {lit}`case zero`.
In {lit}`case succ`, {lit}`n_ih✝` corresponds to the induction hypothesis, while the whole of {lit}`case succ` is the induction step.
The next step in writing the proof is to focus on each of the two goals in turn.
Just as {anchorTerm others}`pure ()` can be used in a {kw}`do` block to indicate “do nothing”, the tactic language has a statement {kw}`skip` that also does nothing.
This can be used when Lean's syntax requires a tactic, but it's not yet clear which one should be used.
Adding {kw}`with` to the end of the {kw}`induction` statement provides a syntax that is similar to pattern matching:
```anchor plusR_ind_zero_left_2a
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => skip
| succ n ih => skip
```
Each of the two {kw}`skip` statements has a message associated with it.
The first shows the base case:
```anchorError plusR_ind_zero_left_2a
unsolved goals
case zero
⊢ 0 = Nat.plusR 0 0
```
The second shows the induction step:
```anchorError plusR_ind_zero_left_2b
unsolved goals
case succ
n : Nat
ih : n = Nat.plusR 0 n
⊢ n + 1 = Nat.plusR 0 (n + 1)
```
In the induction step, the inaccessible names with daggers have been replaced with the names provided after {lit}`succ`, namely {anchorName plusR_ind_zero_left_2a}`n` and {anchorName plusR_ind_zero_left_2a}`ih`.
The cases after {kw}`induction`{lit}` ...`{kw}`with` are not patterns: they consist of the name of a goal followed by zero or more names.
The names are used for assumptions introduced in the goal; it is an error to provide more names than the goal introduces:
```anchor plusR_ind_zero_left_3
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => skip
| succ n ih lots of names => skip
```
```anchorError plusR_ind_zero_left_3
Too many variable names provided at alternative `succ`: 5 provided, but 2 expected
```
Focusing on the base case, the {kw}`rfl` tactic works just as well inside of the {kw}`induction` tactic as it does in a recursive function:
```anchor plusR_ind_zero_left_4
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih => skip
```
In the recursive function version of the proof, a type annotation made the expected type something that was easier to understand.
In the tactic language, there are a number of specific ways to transform a goal to make it easier to solve.
The {kw}`unfold` tactic replaces a defined name with its definition:
```anchor plusR_ind_zero_left_5
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
unfold Nat.plusR
```
Now, the right-hand side of the equality in the goal has become {anchorTerm others}`Nat.plusR 0 n + 1` instead of {anchorTerm others}`Nat.plusR 0 (Nat.succ n)`:
```anchorError plusR_ind_zero_left_5
unsolved goals
case succ
n : Nat
ih : n = Nat.plusR 0 n
⊢ n + 1 = Nat.plusR 0 n + 1
```
Instead of appealing to functions like {anchorName plusR_succ_left (module:=Examples.DependentTypes.Pitfalls)}`congrArg` and operators like {anchorTerm appendR (module:=Examples.DependentTypes.Pitfalls)}`▸`, there are tactics that allow equality proofs to be used to transform proof goals.
One of the most important is {kw}`rw`, which takes a list of equality proofs and replaces the left side with the right side in the goal.
This almost does the right thing in {anchorName plusR_ind_zero_left_6}`plusR_zero_left`:
```anchor plusR_ind_zero_left_6
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
unfold Nat.plusR
rw [ih]
```
However, the direction of the rewrite was incorrect.
Replacing {anchorName others}`n` with {anchorTerm others}`Nat.plusR 0 n` made the goal more complicated rather than less complicated:
```anchorError plusR_ind_zero_left_6
unsolved goals
case succ
n : Nat
ih : n = Nat.plusR 0 n
⊢ Nat.plusR 0 n + 1 = Nat.plusR 0 (Nat.plusR 0 n) + 1
```
This can be remedied by placing a left arrow before {anchorName plusR_zero_left_done}`ih` in the call to {kw}`rw`, which instructs it to replace the right-hand side of the equality with the left-hand side:
```anchor plusR_zero_left_done
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
unfold Nat.plusR
rw [←ih]
```
This rewrite makes both sides of the equation identical, and Lean takes care of the {kw}`rfl` on its own.
The proof is complete.
# Tactic Golf
%%%
tag := "tactic-golf"
%%%
So far, the tactic language has not shown its true value.
The above proof is no shorter than the recursive function; it's merely written in a domain-specific language instead of the full Lean language.
But proofs with tactics can be shorter, easier, and more maintainable.
Just as a lower score is better in the game of golf, a shorter proof is better in the game of tactic golf.
The induction step of {anchorName plusR_zero_left_golf_1}`plusR_zero_left` can be proved using the simplification tactic {tactic}`simp`.
Using {tactic}`simp` on its own does not help:
```anchor plusR_zero_left_golf_1
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
simp
```
```anchorError plusR_zero_left_golf_1
`simp` made no progress
```
However, {tactic}`simp` can be configured to make use of a set of definitions.
Just like {kw}`rw`, these arguments are provided in a list.
Asking {tactic}`simp` to take the definition of {anchorName plusR_zero_left_golf_1}`Nat.plusR` into account leads to a simpler goal:
```anchor plusR_zero_left_golf_2
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
simp [Nat.plusR]
```
```anchorError plusR_zero_left_golf_2
unsolved goals
case succ
n : Nat
ih : n = Nat.plusR 0 n
⊢ n = Nat.plusR 0 n
```
In particular, the goal is now identical to the induction hypothesis.
In addition to automatically proving simple equality statements, the simplifier automatically replaces goals like {anchorTerm others}`Nat.succ A = Nat.succ B` with {anchorTerm others}`A = B`.
Because the induction hypothesis {anchorName plusR_zero_left_golf_3}`ih` has exactly the right type, the {kw}`exact` tactic can indicate that it should be used:
```anchor plusR_zero_left_golf_3
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
simp [Nat.plusR]
exact ih
```
However, the use of {kw}`exact` is somewhat fragile.
Renaming the induction hypothesis, which may happen while “golfing” the proof, would cause this proof to stop working.
The {kw}`assumption` tactic solves the current goal if _any_ of the assumptions match it:
```anchor plusR_zero_left_golf_4
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k with
| zero => rfl
| succ n ih =>
simp [Nat.plusR]
assumption
```
This proof is no shorter than the prior proof that used unfolding and explicit rewriting.
However, a series of transformations can make it much shorter, taking advantage of the fact that {tactic}`simp` can solve many kinds of goals.
The first step is to drop the {kw}`with` at the end of {kw}`induction`.
For structured, readable proofs, the {kw}`with` syntax is convenient.
It complains if any cases are missing, and it shows the structure of the induction clearly.
But shortening proofs can often require a more liberal approach.
Using {kw}`induction` without {kw}`with` simply results in a proof state with two goals.
The {kw}`case` tactic can be used to select one of them, just as in the branches of the {kw}`induction`{lit}` ...`{kw}`with` tactic.
In other words, the following proof is equivalent to the prior proof:
```anchor plusR_zero_left_golf_5
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k
case zero => rfl
case succ n ih =>
simp [Nat.plusR]
assumption
```
In a context with a single goal (namely, {anchorTerm plusR_zero_left_golf_6a}`k = Nat.plusR 0 k`), the {anchorTerm plusR_zero_left_golf_5}`induction k` tactic yields two goals.
In general, a tactic will either fail with an error or take a goal and transform it into zero or more new goals.
Each new goal represents what remains to be proved.
If the result is zero goals, then the tactic was a success, and that part of the proof is done.
The {kw}`<;>` operator takes two tactics as arguments, resulting in a new tactic.
{lit}`T1 `{kw}`<;>`{lit}` T2` applies {lit}`T1` to the current goal, and then applies {lit}`T2` in _all_ goals created by {lit}`T1`.
In other words, {kw}`<;>` enables a general tactic that can solve many kinds of goals to be used on multiple new goals all at once.
One such general tactic is {tactic}`simp`.
Because {tactic}`simp` can both complete the proof of the base case and make progress on the proof of the induction step, using it with {kw}`induction` and {kw}`<;>` shortens the proof:
```anchor plusR_zero_left_golf_6a
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k <;> simp [Nat.plusR]
```
This results in only a single goal, the transformed induction step:
```anchorError plusR_zero_left_golf_6a
unsolved goals
case succ
n✝ : Nat
a✝ : n✝ = Nat.plusR 0 n✝
⊢ n✝ = Nat.plusR 0 n✝
```
Running {kw}`assumption` in this goal completes the proof:
```anchor plusR_zero_left_golf_6
theorem plusR_zero_left (k : Nat) : k = Nat.plusR 0 k := by
induction k <;> simp [Nat.plusR] <;> assumption
```
Here, {kw}`exact` would not have been possible, because {lit}`ih` was never explicitly named.
For beginners, this proof is not easier to read.
However, a common pattern for expert users is to take care of a number of simple cases with powerful tactics like {tactic}`simp`, allowing them to focus the text of the proof on the interesting cases.
Additionally, these proofs tend to be more robust in the face of small changes to the functions and datatypes involved in the proof.
The game of tactic golf is a useful part of developing good taste and style when writing proofs.
# Induction on Other Datatypes
%%%
tag := "induction-other-types"
%%%
Mathematical induction proves a statement for natural numbers by providing a base case for {anchorName others}`Nat.zero` and an induction step for {anchorName others}`Nat.succ`.
The principle of induction is also valid for other datatypes.
Constructors without recursive arguments form the base cases, while constructors with recursive arguments form the induction steps.
The ability to carry out proofs by induction is the very reason why they are called _inductive_ datatypes.
One example of this is induction on binary trees.
Induction on binary trees is a proof technique where a statement is proven for _all_ binary trees in two steps:
1. The statement is shown to hold for {anchorName TreeCtors}`BinTree.leaf`. This is called the base case.
2. Under the assumption that the statement holds for some arbitrarily chosen trees {anchorName TreeCtors}`l` and {anchorName TreeCtors}`r`, it is shown to hold for {anchorTerm TreeCtors}`BinTree.branch l x r`, where {anchorName TreeCtors}`x` is an arbitrarily-chosen new data point. This is called the _induction step_. The assumptions that the statement holds for {anchorName TreeCtors}`l` and {anchorName TreeCtors}`r` are called the _induction hypotheses_.
{anchorName BinTree_count}`BinTree.count` counts the number of branches in a tree:
```anchor BinTree_count
def BinTree.count : BinTree α → Nat
| .leaf => 0
| .branch l _ r =>
1 + l.count + r.count
```
{ref "leading-dot-notation"}[Mirroring a tree] does not change the number of branches in it.
This can be proven using induction on trees.
The first step is to state the theorem and invoke {kw}`induction`:
```anchor mirror_count_0a
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => skip
| branch l x r ihl ihr => skip
```
The base case states that counting the mirror of a leaf is the same as counting the leaf:
```anchorError mirror_count_0a
unsolved goals
case leaf
α : Type
⊢ leaf.mirror.count = leaf.count
```
The induction step allows the assumption that mirroring the left and right subtrees won't affect their branch counts, and requests a proof that mirroring a branch with these subtrees also preserves the overall branch count:
```anchorError mirror_count_0b
unsolved goals
case branch
α : Type
l : BinTree α
x : α
r : BinTree α
ihl : l.mirror.count = l.count
ihr : r.mirror.count = r.count
⊢ (l.branch x r).mirror.count = (l.branch x r).count
```
The base case is true because mirroring {anchorName mirror_count_1}`leaf` results in {anchorName mirror_count_1}`leaf`, so the left and right sides are definitionally equal.
This can be expressed by using {tactic}`simp` with instructions to unfold {anchorName mirror_count_1}`BinTree.mirror`:
```anchor mirror_count_1
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr => skip
```
In the induction step, nothing in the goal immediately matches the induction hypotheses.
Simplifying using the definitions of {anchorName mirror_count_2}`BinTree.count` and {anchorName mirror_count_2}`BinTree.mirror` reveals the relationship:
```anchor mirror_count_2
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr =>
simp [BinTree.mirror, BinTree.count]
```
```anchorError mirror_count_2
unsolved goals
case branch
α : Type
l : BinTree α
x : α
r : BinTree α
ihl : l.mirror.count = l.count
ihr : r.mirror.count = r.count
⊢ 1 + r.mirror.count + l.mirror.count = 1 + l.count + r.count
```
Both induction hypotheses can be used to rewrite the left-hand side of the goal into something almost like the right-hand side:
```anchor mirror_count_3
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr =>
simp [BinTree.mirror, BinTree.count]
rw [ihl, ihr]
```
```anchorError mirror_count_3
unsolved goals
case branch
α : Type
l : BinTree α
x : α
r : BinTree α
ihl : l.mirror.count = l.count
ihr : r.mirror.count = r.count
⊢ 1 + r.count + l.count = 1 + l.count + r.count
```
The {tactic}`simp` tactic can use additional arithmetic identities when passed the {anchorTerm mirror_count_4}`+arith` option.
It is enough to prove this goal, yielding:
```anchor mirror_count_4
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr =>
simp [BinTree.mirror, BinTree.count]
rw [ihl, ihr]
simp +arith
```
In addition to definitions to be unfolded, the simplifier can also be passed names of equality proofs to use as rewrites while it simplifies proof goals.
{anchorName mirror_count_5}`BinTree.mirror_count` can also be written:
```anchor mirror_count_5
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr =>
simp +arith [BinTree.mirror, BinTree.count, ihl, ihr]
```
As proofs grow more complicated, listing assumptions by hand can become tedious.
Furthermore, manually writing assumption names can make it more difficult to re-use proof steps for multiple subgoals.
The argument {lit}`*` to {tactic}`simp` or {kw}`simp +arith` instructs them to use _all_ assumptions while simplifying or solving the goal.
In other words, the proof could also be written:
```anchor mirror_count_6
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t with
| leaf => simp [BinTree.mirror]
| branch l x r ihl ihr =>
simp +arith [BinTree.mirror, BinTree.count, *]
```
Because both branches are using the simplifier, the proof can be reduced to:
```anchor mirror_count_7
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t <;> simp +arith [BinTree.mirror, BinTree.count, *]
```
# The {lit}`grind` Tactic
%%%
tag := "grind"
%%%
The {tactic}`grind` tactic can automatically prove many theorems.
Like {tactic}`simp`, it accepts an optional list of additional facts to take into consideration or functions to unfold; unlike {tactic}`simp`, it automatically takes local hypotheses into consideration.
Additionally, {tactic}`grind`'s support for reasoning about specific mathematical domains is far stronger than {tactic}`simp`'s arithmetic support.
The proof of {anchorName mirror_count_8}`BinTree.mirror_count` can rewritten to use {tactic}`grind`:
```anchor mirror_count_8
theorem BinTree.mirror_count (t : BinTree α) :
t.mirror.count = t.count := by
induction t <;> grind [BinTree.mirror, BinTree.count]
```
Because the proofs in this book are fairly modest, most of them do not provide an opportunity for {tactic}`grind` to show its full power.
However, it is very convenient in some of the later proofs in the book.
# Exercises
%%%
tag := "tactics-induction-proofs-exercises"
%%%
* Prove {anchorName plusR_succ_left (module:=Examples.DependentTypes.Pitfalls)}`plusR_succ_left` using the {kw}`induction`{lit}` ...`{kw}`with` tactic.
* Rewrite the proof of {anchorName plusR_succ_left (module:=Examples.DependentTypes.Pitfalls)}`plusR_succ_left` to use {kw}`<;>` in a single line.
* Prove that appending lists is associative using induction on lists:
```anchorTerm ex
theorem List.append_assoc (xs ys zs : List α) :
xs ++ (ys ++ zs) = (xs ++ ys) ++ zs
``` |
fp-lean/book/FPLean/NextSteps.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso.Code.External
open FPLean
#doc (Manual) "Next Steps" =>
%%%
tag := "next-steps"
htmlSplit := .never
%%%
This book introduces the very basics of functional programming in Lean, including a tiny amount of interactive theorem proving.
Using dependently-typed functional languages like Lean is a deep topic, and much can be said.
Depending on your interests, the following resources might be useful for learning Lean 4.
# Learning Lean
%%%
tag := "learning-lean"
%%%
Lean 4 itself is described in the following resources:
* [Theorem Proving in Lean 4](https://lean-lang.org/theorem_proving_in_lean4/) is a tutorial on writing proofs using Lean.
* [The Lean 4 Manual](https://lean-lang.org/doc/reference/latest/) provides a detailed description of the language and its features.
* [How To Prove It With Lean](https://djvelleman.github.io/HTPIwL/) is a Lean-based accompaniment to the well-regarded textbook [_How To Prove It_](https://www.cambridge.org/highereducation/books/how-to-prove-it/6D2965D625C6836CD4A785A2C843B3DA) that provides an introduction to writing paper-and-pencil mathematical proofs.
* [Metaprogramming in Lean 4](https://github.com/arthurpaulino/lean4-metaprogramming-book) provides an overview of Lean's extension mechanisms, from infix operators and notations to macros, custom tactics, and full-on custom embedded languages.
* [Functional Programming in Lean](https://lean-lang.org/functional_programming_in_lean/) may be interesting to readers who enjoy jokes about recursion.
However, the best way to continue learning Lean is to start reading and writing code, consulting the documentation when you get stuck.
Additionally, the [Lean Zulip](https://leanprover.zulipchat.com/) is an excellent place to meet other Lean users, ask for help, and help others.
# Mathematics in Lean
%%%
tag := none
%%%
A wide selection of learning resources for mathematicians are available at [the community site](https://leanprover-community.github.io/learn.html).
# Using Dependent Types in Computer Science
%%%
tag := none
%%%
Rocq is a language that has a lot in common with Lean.
For computer scientists, the [Software Foundations](https://softwarefoundations.cis.upenn.edu/) series of interactive textbooks provides an excellent introduction to applications of Rocq in computer science.
The fundamental ideas of Lean and Rocq are very similar, and skills are readily transferable between the systems.
# Programming with Dependent Types
%%%
tag := none
%%%
For programmers who are interested in learning to use indexed families and dependent types to structure programs, Edwin Brady's [_Type Driven Development with Idris_](https://www.manning.com/books/type-driven-development-with-idris) provides an excellent introduction.
Like Rocq, Idris is a close cousin of Lean, though it lacks tactics.
# Understanding Dependent Types
%%%
tag := none
%%%
[_The Little Typer_](https://thelittletyper.com/) is a book for programmers who haven't formally studied logic or the theory of programming languages, but who want to build an understanding of the core ideas of dependent type theory.
While all of the above resources aim to be as practical as possible, _The Little Typer_ presents an approach to dependent type theory where the very basics are built up from scratch, using only concepts from programming.
Disclaimer: the author of _Functional Programming in Lean_ is also an author of _The Little Typer_. |
fp-lean/book/FPLean/Monads.lean | import VersoManual
import FPLean.Examples
import FPLean.Monads.Class
import FPLean.Monads.Arithmetic
import FPLean.Monads.Do
import FPLean.Monads.IO
import FPLean.Monads.Conveniences
import FPLean.Monads.Summary
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.Monads"
#doc (Manual) "Monads" =>
%%%
tag := "monads"
%%%
In C# and Kotlin, the {CSharp}`?.` operator is a way to look up a property or call a method on a potentially-null value.
If the receiver is {CSharp}`null`, the whole expression is null.
Otherwise, the underlying non-{CSharp}`null` value receives the call.
Uses of {CSharp}`?.` can be chained, in which case the first {Kotlin}`null` result terminates the chain of lookups.
Chaining null-checks like this is much more convenient than writing and maintaining deeply nested {kw}`if`s.
Similarly, exceptions are significantly more convenient than manually checking and propagating error codes.
At the same time, logging is easiest to accomplish by having a dedicated logging framework, rather than having each function return both its log results and its return value.
Chained null checks and exceptions typically require language designers to anticipate this use case, while logging frameworks typically make use of side effects to decouple code that logs from the accumulation of the logs.
# One API, Many Applications
%%%
tag := "monad-api-examples"
%%%
All these features and more can be implemented in library code as instances of a common API called {moduleName}`Monad`.
Lean provides dedicated syntax that makes this API convenient to use, but can also get in the way of understanding what is going on behind the scenes.
This chapter begins with the nitty-gritty presentation of manually nesting null checks, and builds from there to the convenient, general API.
Please suspend your disbelief in the meantime.
## Checking for {lit}`none`: Don't Repeat Yourself
%%%
tag := "example-option-monad"
%%%
:::paragraph
In Lean, pattern matching can be used to chain checks for null.
Getting the first entry from a list can just use the optional indexing notation:
```anchor first
def first (xs : List α) : Option α :=
xs[0]?
```
:::
:::paragraph
The result must be an {anchorName first}`Option` because empty lists have no first entry.
Extracting the first and third entries requires a check that each is not {moduleName}`none`:
```anchor firstThird
def firstThird (xs : List α) : Option (α × α) :=
match xs[0]? with
| none => none
| some first =>
match xs[2]? with
| none => none
| some third =>
some (first, third)
```
Similarly, extracting the first, third, and fifth entries requires more checks that the values are not {moduleName}`none`:
```anchor firstThirdFifth
def firstThirdFifth (xs : List α) : Option (α × α × α) :=
match xs[0]? with
| none => none
| some first =>
match xs[2]? with
| none => none
| some third =>
match xs[4]? with
| none => none
| some fifth =>
some (first, third, fifth)
```
And adding the seventh entry to this sequence begins to become quite unmanageable:
```anchor firstThirdFifthSeventh
def firstThirdFifthSeventh (xs : List α) : Option (α × α × α × α) :=
match xs[0]? with
| none => none
| some first =>
match xs[2]? with
| none => none
| some third =>
match xs[4]? with
| none => none
| some fifth =>
match xs[6]? with
| none => none
| some seventh =>
some (first, third, fifth, seventh)
```
:::
:::paragraph
The fundamental problem with this code is that it addresses two concerns: extracting the numbers and checking that all of them are present.
The second concern is addressed by copying and pasting the code that handles the {moduleName}`none` case.
It is often good style to lift a repetitive segment into a helper function:
```anchor andThenOption
def andThen (opt : Option α) (next : α → Option β) : Option β :=
match opt with
| none => none
| some x => next x
```
This helper, which is used similarly to {CSharp}`?.` in C# and Kotlin, takes care of propagating {moduleName}`none` values.
It takes two arguments: an optional value and a function to apply when the value is not {moduleName}`none`.
If the first argument is {moduleName}`none`, then the helper returns {moduleName}`none`.
If the first argument is not {moduleName}`none`, then the function is applied to the contents of the {moduleName}`some` constructor.
:::
:::paragraph
Now, {anchorName firstThirdandThen}`firstThird` can be rewritten to use {anchorName firstThirdandThen}`andThen` instead of pattern matching:
```anchor firstThirdandThen
def firstThird (xs : List α) : Option (α × α) :=
andThen xs[0]? fun first =>
andThen xs[2]? fun third =>
some (first, third)
```
In Lean, functions don't need to be enclosed in parentheses when passed as arguments.
The following equivalent definition uses more parentheses and indents the bodies of functions:
```anchor firstThirdandThenExpl
def firstThird (xs : List α) : Option (α × α) :=
andThen xs[0]? (fun first =>
andThen xs[2]? (fun third =>
some (first, third)))
```
The {anchorName firstThirdandThenExpl}`andThen` helper provides a sort of “pipeline” through which values flow, and the version with the somewhat unusual indentation is more suggestive of this fact.
Improving the syntax used to write {anchorName firstThirdandThenExpl}`andThen` can make these computations even easier to understand.
:::
### Infix Operators
%%%
tag := "defining-infix-operators"
%%%
In Lean, infix operators can be declared using the {kw}`infix`, {kw}`infixl`, and {kw}`infixr` commands, which create (respectively) non-associative, left-associative, and right-associative operators.
When used multiple times in a row, a {deftech}_left associative_ operator stacks up the opening parentheses on the left side of the expression.
The addition operator {lit}`+` is left associative, so {anchorTerm plusFixity}`w + x + y + z` is equivalent to {anchorTerm plusFixity}`(((w + x) + y) + z)`.
The exponentiation operator {lit}`^` is right associative, so {anchorTerm powFixity}`w ^ x ^ y ^ z` is equivalent to {anchorTerm powFixity}`w ^ (x ^ (y ^ z))`.
Comparison operators such as {lit}`<` are non-associative, so {lit}`x < y < z` is a syntax error and requires manual parentheses.
:::paragraph
The following declaration makes {anchorName andThenOptArr}`andThen` into an infix operator:
```anchor andThenOptArr
infixl:55 " ~~> " => andThen
```
The number following the colon declares the {deftech}_precedence_ of the new infix operator.
In ordinary mathematical notation, {anchorTerm plusTimesPrec}`x + y * z` is equivalent to {anchorTerm plusTimesPrec}`x + (y * z)` even though both {lit}`+` and {lit}`*` are left associative.
In Lean, {lit}`+` has precedence 65 and {lit}`*` has precedence 70.
Higher-precedence operators are applied before lower-precedence operators.
According to the declaration of {lit}`~~>`, both {lit}`+` and {lit}`*` have higher precedence, and thus apply first.
Typically, figuring out the most convenient precedences for a group of operators requires some experimentation and a large collection of examples.
:::
Following the new infix operator is a double arrow {lit}`=>`, which specifies the named function to be used for the infix operator.
Lean's standard library uses this feature to define {lit}`+` and {lit}`*` as infix operators that point at {moduleName}`HAdd.hAdd` and {moduleName}`HMul.hMul`, respectively, allowing type classes to be used to overload the infix operators.
Here, however, {anchorName firstThirdandThen}`andThen` is just an ordinary function.
:::paragraph
Having defined an infix operator for {anchorName andThenOptArr}`andThen`, {anchorName firstThirdInfix (show := firstThird)}`firstThirdInfix` can be rewritten in a way that brings the “pipeline” feeling of {moduleName}`none`-checks front and center:
```anchor firstThirdInfix
def firstThirdInfix (xs : List α) : Option (α × α) :=
xs[0]? ~~> fun first =>
xs[2]? ~~> fun third =>
some (first, third)
```
This style is much more concise when writing larger functions:
```anchor firstThirdFifthSeventInfix
def firstThirdFifthSeventh (xs : List α) : Option (α × α × α × α) :=
xs[0]? ~~> fun first =>
xs[2]? ~~> fun third =>
xs[4]? ~~> fun fifth =>
xs[6]? ~~> fun seventh =>
some (first, third, fifth, seventh)
```
:::
## Propagating Error Messages
%%%
tag := "example-except-monad"
%%%
Pure functional languages such as Lean have no built-in exception mechanism for error handling, because throwing or catching an exception is outside of the step-by-step evaluation model for expressions.
However, functional programs certainly need to handle errors.
In the case of {anchorName firstThirdFifthSeventInfix}`firstThirdFifthSeventh`, it is likely relevant for a user to know just how long the list was and where the lookup failed.
:::paragraph
This is typically accomplished by defining a datatype that can be either an error or a result, and translating functions with exceptions into functions that return this datatype:
```anchor Except
inductive Except (ε : Type) (α : Type) where
| error : ε → Except ε α
| ok : α → Except ε α
deriving BEq, Hashable, Repr
```
The type variable {anchorName Except}`ε` stands for the type of errors that can be produced by the function.
Callers are expected to handle both errors and successes, which makes the type variable {anchorName Except}`ε` play a role that is a bit like that of a list of checked exceptions in Java.
:::
:::paragraph
Similarly to {anchorName first}`Option`, {anchorName Except}`Except` can be used to indicate a failure to find an entry in a list.
In this case, the error type is a {moduleName}`String`:
```anchor getExcept
def get (xs : List α) (i : Nat) : Except String α :=
match xs[i]? with
| none => Except.error s!"Index {i} not found (maximum is {xs.length - 1})"
| some x => Except.ok x
```
Looking up an in-bounds value yields an {anchorName ExceptExtra}`Except.ok`:
```anchor ediblePlants
def ediblePlants : List String :=
["ramsons", "sea plantain", "sea buckthorn", "garden nasturtium"]
```
```anchor success
#eval get ediblePlants 2
```
```anchorInfo success
Except.ok "sea buckthorn"
```
Looking up an out-of-bounds value yields an {anchorName ExceptExtra}`Except.error`:
```anchor failure
#eval get ediblePlants 4
```
```anchorInfo failure
Except.error "Index 4 not found (maximum is 3)"
```
:::
:::paragraph
A single list lookup can conveniently return a value or an error:
```anchor firstExcept
def first (xs : List α) : Except String α :=
get xs 0
```
However, performing two list lookups requires handling potential failures:
```anchor firstThirdExcept
def firstThird (xs : List α) : Except String (α × α) :=
match get xs 0 with
| Except.error msg => Except.error msg
| Except.ok first =>
match get xs 2 with
| Except.error msg => Except.error msg
| Except.ok third =>
Except.ok (first, third)
```
Adding another list lookup to the function requires still more error handling:
```anchor firstThirdFifthExcept
def firstThirdFifth (xs : List α) : Except String (α × α × α) :=
match get xs 0 with
| Except.error msg => Except.error msg
| Except.ok first =>
match get xs 2 with
| Except.error msg => Except.error msg
| Except.ok third =>
match get xs 4 with
| Except.error msg => Except.error msg
| Except.ok fifth =>
Except.ok (first, third, fifth)
```
And one more list lookup begins to become quite unmanageable:
```anchor firstThirdFifthSeventhExcept
def firstThirdFifthSeventh (xs : List α) : Except String (α × α × α × α) :=
match get xs 0 with
| Except.error msg => Except.error msg
| Except.ok first =>
match get xs 2 with
| Except.error msg => Except.error msg
| Except.ok third =>
match get xs 4 with
| Except.error msg => Except.error msg
| Except.ok fifth =>
match get xs 6 with
| Except.error msg => Except.error msg
| Except.ok seventh =>
Except.ok (first, third, fifth, seventh)
```
:::
:::paragraph
Once again, a common pattern can be factored out into a helper.
Each step through the function checks for an error, and only proceeds with the rest of the computation if the result was a success.
A new version of {anchorName andThenExcept}`andThen` can be defined for {anchorName andThenExcept}`Except`:
```anchor andThenExcept
def andThen (attempt : Except e α) (next : α → Except e β) : Except e β :=
match attempt with
| Except.error msg => Except.error msg
| Except.ok x => next x
```
Just as with {anchorName first}`Option`, this version of {anchorName andThenExcept}`andThen` allows a more concise definition of {anchorName firstThirdAndThenExcept}`firstThird'`:
```anchor firstThirdAndThenExcept
def firstThird' (xs : List α) : Except String (α × α) :=
andThen (get xs 0) fun first =>
andThen (get xs 2) fun third =>
Except.ok (first, third)
```
:::
:::paragraph
In both the {anchorName first}`Option` and {anchorName andThenExcept}`Except` case, there are two repeating patterns: there is the checking of intermediate results at each step, which has been factored out into {anchorName andThenExcept}`andThen`, and there is the final successful result, which is {moduleName}`some` or {anchorName andThenExcept}`Except.ok`, respectively.
For the sake of convenience, success can be factored out into a helper called {anchorName okExcept}`ok`:
```anchor okExcept
def ok (x : α) : Except ε α := Except.ok x
```
Similarly, failure can be factored out into a helper called {anchorName failExcept}`fail`:
```anchor failExcept
def fail (err : ε) : Except ε α := Except.error err
```
Using {anchorName okExcept}`ok` and {anchorName failExcept}`fail` makes {anchorName getExceptEffects}`get` a little more readable:
```anchor getExceptEffects
def get (xs : List α) (i : Nat) : Except String α :=
match xs[i]? with
| none => fail s!"Index {i} not found (maximum is {xs.length - 1})"
| some x => ok x
```
:::
:::paragraph
After adding the infix declaration for {anchorName andThenExceptInfix}`andThen`, {anchorName firstThirdInfixExcept}`firstThird` can be just as concise as the version that returns an {anchorName first}`Option`:
```anchor andThenExceptInfix
infixl:55 " ~~> " => andThen
```
```anchor firstThirdInfixExcept
def firstThird (xs : List α) : Except String (α × α) :=
get xs 0 ~~> fun first =>
get xs 2 ~~> fun third =>
ok (first, third)
```
The technique scales similarly to larger functions:
```anchor firstThirdFifthSeventInfixExcept
def firstThirdFifthSeventh (xs : List α) : Except String (α × α × α × α) :=
get xs 0 ~~> fun first =>
get xs 2 ~~> fun third =>
get xs 4 ~~> fun fifth =>
get xs 6 ~~> fun seventh =>
ok (first, third, fifth, seventh)
```
:::
## Logging
%%%
tag := "logging"
%%%
:::paragraph
A number is even if dividing it by 2 leaves no remainder:
```anchor isEven
def isEven (i : Int) : Bool :=
i % 2 == 0
```
The function {anchorName sumAndFindEvensDirect}`sumAndFindEvens` computes the sum of a list while remembering the even numbers encountered along the way:
```anchor sumAndFindEvensDirect
def sumAndFindEvens : List Int → List Int × Int
| [] => ([], 0)
| i :: is =>
let (moreEven, sum) := sumAndFindEvens is
(if isEven i then i :: moreEven else moreEven, sum + i)
```
:::
:::paragraph
This function is a simplified example of a common pattern.
Many programs need to traverse a data structure once, while both computing a main result and accumulating some kind of tertiary extra result.
One example of this is logging: a program that is an {moduleName}`IO` action can always log to a file on disk, but because the disk is outside of the mathematical world of Lean functions, it becomes much more difficult to prove things about logs based on {moduleName}`IO`.
Another example is a function that computes the sum of all the nodes in a tree with an inorder traversal, while simultaneously recording each nodes visited:
```anchor inorderSum
def inorderSum : BinTree Int → List Int × Int
| BinTree.leaf => ([], 0)
| BinTree.branch l x r =>
let (leftVisited, leftSum) := inorderSum l
let (hereVisited, hereSum) := ([x], x)
let (rightVisited, rightSum) := inorderSum r
(leftVisited ++ hereVisited ++ rightVisited,
leftSum + hereSum + rightSum)
```
:::
Both {anchorName sumAndFindEvensDirect}`sumAndFindEvens` and {anchorName inorderSum}`inorderSum` have a common repetitive structure.
Each step of computation returns a pair that consists of a list of data that have been saved along with the primary result.
The lists are then appended, and the primary result is computed and paired with the appended lists.
The common structure becomes more apparent with a small rewrite of {anchorName sumAndFindEvensDirectish}`sumAndFindEvens` that more cleanly separates the concerns of saving even numbers and computing the sum:
```anchor sumAndFindEvensDirectish
def sumAndFindEvens : List Int → List Int × Int
| [] => ([], 0)
| i :: is =>
let (moreEven, sum) := sumAndFindEvens is
let (evenHere, ()) := (if isEven i then [i] else [], ())
(evenHere ++ moreEven, sum + i)
```
For the sake of clarity, a pair that consists of an accumulated result together with a value can be given its own name:
```anchor WithLog
structure WithLog (logged : Type) (α : Type) where
log : List logged
val : α
```
Similarly, the process of saving a list of accumulated results while passing a value on to the next step of a computation can be factored out into a helper, once again named {anchorName andThenWithLog}`andThen`:
```anchor andThenWithLog
def andThen (result : WithLog α β) (next : β → WithLog α γ) : WithLog α γ :=
let {log := thisOut, val := thisRes} := result
let {log := nextOut, val := nextRes} := next thisRes
{log := thisOut ++ nextOut, val := nextRes}
```
In the case of errors, {anchorName okWithLog}`ok` represents an operation that always succeeds.
Here, however, it is an operation that simply returns a value without logging anything:
```anchor okWithLog
def ok (x : β) : WithLog α β := {log := [], val := x}
```
Just as {anchorName Except}`Except` provides {anchorName failExcept}`fail` as a possibility, {anchorName WithLog}`WithLog` should allow items to be added to a log.
This has no interesting return value associated with it, so it returns {anchorName save}`Unit`:
```anchor save
def save (data : α) : WithLog α Unit :=
{log := [data], val := ()}
```
{anchorName WithLog}`WithLog`, {anchorName andThenWithLog}`andThen`, {anchorName okWithLog}`ok`, and {anchorName save}`save` can be used to separate the logging concern from the summing concern in both programs:
```anchor sumAndFindEvensAndThen
def sumAndFindEvens : List Int → WithLog Int Int
| [] => ok 0
| i :: is =>
andThen (if isEven i then save i else ok ()) fun () =>
andThen (sumAndFindEvens is) fun sum =>
ok (i + sum)
```
```anchor inorderSumAndThen
def inorderSum : BinTree Int → WithLog Int Int
| BinTree.leaf => ok 0
| BinTree.branch l x r =>
andThen (inorderSum l) fun leftSum =>
andThen (save x) fun () =>
andThen (inorderSum r) fun rightSum =>
ok (leftSum + x + rightSum)
```
And, once again, the infix operator helps put focus on the correct steps:
```anchor infixAndThenLog
infixl:55 " ~~> " => andThen
```
```anchor withInfixLogging
def sumAndFindEvens : List Int → WithLog Int Int
| [] => ok 0
| i :: is =>
(if isEven i then save i else ok ()) ~~> fun () =>
sumAndFindEvens is ~~> fun sum =>
ok (i + sum)
def inorderSum : BinTree Int → WithLog Int Int
| BinTree.leaf => ok 0
| BinTree.branch l x r =>
inorderSum l ~~> fun leftSum =>
save x ~~> fun () =>
inorderSum r ~~> fun rightSum =>
ok (leftSum + x + rightSum)
```
## Numbering Tree Nodes
%%%
tag := "numbering-tree-nodes"
%%%
An {deftech}_inorder numbering_ of a tree associates each data point in the tree with the step it would be visited at in an inorder traversal of the tree.
For example, consider {anchorName aTree}`aTree`:
```anchor aTree
open BinTree in
def aTree :=
branch
(branch
(branch leaf "a" (branch leaf "b" leaf))
"c"
leaf)
"d"
(branch leaf "e" leaf)
```
Its inorder numbering is:
```anchorInfo numberATree
BinTree.branch
(BinTree.branch
(BinTree.branch (BinTree.leaf) (0, "a") (BinTree.branch (BinTree.leaf) (1, "b") (BinTree.leaf)))
(2, "c")
(BinTree.leaf))
(3, "d")
(BinTree.branch (BinTree.leaf) (4, "e") (BinTree.leaf))
```
:::paragraph
Trees are most naturally processed with recursive functions, but the usual pattern of recursion on trees makes it difficult to compute an inorder numbering.
This is because the highest number assigned anywhere in the left subtree is used to determine the numbering of a node's data value, and then again to determine the starting point for numbering the right subtree.
In an imperative language, this issue can be worked around by using a mutable variable that contains the next number to be assigned.
The following Python program computes an inorder numbering using a mutable variable:
```includePython "../examples/inorder_python/inordernumbering.py" (anchor := code)
class Branch:
def __init__(self, value, left=None, right=None):
self.left = left
self.value = value
self.right = right
def __repr__(self):
return f'Branch({self.value!r}, left={self.left!r}, right={self.right!r})'
def number(tree):
num = 0
def helper(t):
nonlocal num
if t is None:
return None
else:
new_left = helper(t.left)
new_value = (num, t.value)
num += 1
new_right = helper(t.right)
return Branch(left=new_left, value=new_value, right=new_right)
return helper(tree)
```
The numbering of the Python equivalent of {anchorName aTree}`aTree` is:
```includePython "../examples/inorder_python/inordernumbering.py" (anchor := a_tree)
a_tree = Branch("d",
left=Branch("c",
left=Branch("a", left=None, right=Branch("b")),
right=None),
right=Branch("e"))
```
and its numbering is:
```command inorderpy "inorder_python" (prompt := ">>> ") (show := "number(a_tree)")
python3 inordernumbering.py
```
```commandOut inorderpy "python3 inordernumbering.py"
Branch((3, 'd'), left=Branch((2, 'c'), left=Branch((0, 'a'), left=None, right=Branch((1, 'b'), left=None, right=None)), right=None), right=Branch((4, 'e'), left=None, right=None))
```
:::
Even though Lean does not have mutable variables, a workaround exists.
From the point of view of the rest of the world, the mutable variable can be thought of as having two relevant aspects: its value when the function is called, and its value when the function returns.
In other words, a function that uses a mutable variable can be seen as a function that takes the mutable variable's starting value as an argument, returning a pair of the variable's final value and the function's result.
This final value can then be passed as an argument to the next step.
:::paragraph
Just as the Python example uses an outer function that establishes a mutable variable and an inner helper function that changes the variable, a Lean version of the function uses an outer function that provides the variable's starting value and explicitly returns the function's result along with an inner helper function that threads the variable's value while computing the numbered tree:
```anchor numberDirect
def number (t : BinTree α) : BinTree (Nat × α) :=
let rec helper (n : Nat) : BinTree α → (Nat × BinTree (Nat × α))
| BinTree.leaf => (n, BinTree.leaf)
| BinTree.branch left x right =>
let (k, numberedLeft) := helper n left
let (i, numberedRight) := helper (k + 1) right
(i, BinTree.branch numberedLeft (k, x) numberedRight)
(helper 0 t).snd
```
This code, like the {moduleName}`none`-propagating {anchorName first}`Option` code, the {anchorName exceptNames (show := error)}`Except.error`-propagating {anchorName exceptNames}`Except` code, and the log-accumulating {moduleName}`WithLog` code, commingles two concerns: propagating the value of the counter, and actually traversing the tree to find the result.
Just as in those cases, an {anchorName andThenState}`andThen` helper can be defined to propagate state from one step of a computation to another.
The first step is to give a name to the pattern of taking an input state as an argument and returning an output state together with a value:
```anchor State
def State (σ : Type) (α : Type) : Type :=
σ → (σ × α)
```
:::
:::paragraph
In the case of {anchorName State}`State`, {anchorName okState}`ok` is a function that returns the input state unchanged, along with the provided value:
```anchor okState
def ok (x : α) : State σ α :=
fun s => (s, x)
```
:::
:::paragraph
When working with a mutable variable, there are two fundamental operations: reading the value and replacing it with a new one.
Reading the current value is accomplished with a function that places the input state unmodified into the output state, and also places it into the value field:
```anchor get
def get : State σ σ :=
fun s => (s, s)
```
Writing a new value consists of ignoring the input state, and placing the provided new value into the output state:
```anchor set
def set (s : σ) : State σ Unit :=
fun _ => (s, ())
```
:::
:::paragraph
Finally, two computations that use state can be sequenced by finding both the output state and return value of the first function, then passing them both into the next function:
```anchor andThenState
def andThen (first : State σ α) (next : α → State σ β) : State σ β :=
fun s =>
let (s', x) := first s
next x s'
infixl:55 " ~~> " => andThen
```
:::
:::paragraph
Using {anchorName State}`State` and its helpers, local mutable state can be simulated:
```anchor numberMonadicish
def number (t : BinTree α) : BinTree (Nat × α) :=
let rec helper : BinTree α → State Nat (BinTree (Nat × α))
| BinTree.leaf => ok BinTree.leaf
| BinTree.branch left x right =>
helper left ~~> fun numberedLeft =>
get ~~> fun n =>
set (n + 1) ~~> fun () =>
helper right ~~> fun numberedRight =>
ok (BinTree.branch numberedLeft (n, x) numberedRight)
(helper t 0).snd
```
Because {anchorName State}`State` simulates only a single local variable, {anchorName get}`get` and {anchorName set}`set` don't need to refer to any particular variable name.
:::
## Monads: A Functional Design Pattern
%%%
tag := "monad-as-design-pattern"
%%%
Each of these examples has consisted of:
* A polymorphic type, such as {anchorName first}`Option`, {anchorTerm okExcept}`Except ε`, {anchorTerm save}`WithLog α`, or {anchorTerm andThenState}`State σ`
* An operator {lit}`andThen` that takes care of some repetitive aspect of sequencing programs that have this type
* An operator {lit}`ok` that is (in some sense) the most boring way to use the type
* A collection of other operations, such as {moduleName}`none`, {anchorName failExcept}`fail`, {anchorName save}`save`, and {anchorName get}`get`, that name ways of using the type
This style of API is called a {deftech}_monad_.
While the idea of monads is derived from a branch of mathematics called category theory, no understanding of category theory is needed in order to use them for programming.
The key idea of monads is that each monad encodes a particular kind of side effect using the tools provided by the pure functional language Lean.
For example, {anchorName first}`Option` represents programs that can fail by returning {moduleName}`none`, {moduleName}`Except` represents programs that can throw exceptions, {moduleName}`WithLog` represents programs that accumulate a log while running, and {anchorName State}`State` represents programs with a single mutable variable.
{include 1 FPLean.Monads.Class}
{include 1 FPLean.Monads.Arithmetic}
{include 1 FPLean.Monads.Do}
{include 1 FPLean.Monads.IO}
{include 1 FPLean.Monads.Conveniences}
{include 1 FPLean.Monads.Summary} |
fp-lean/book/FPLean/MonadTransformers.lean | import VersoManual
import FPLean.Examples
import FPLean.MonadTransformers.ReaderIO
import FPLean.MonadTransformers.Transformers
import FPLean.MonadTransformers.Order
import FPLean.MonadTransformers.Do
import FPLean.MonadTransformers.Conveniences
import FPLean.MonadTransformers.Summary
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.Monads"
#doc (Manual) "Monad Transformers" =>
A monad is a way to encode some collection of side effects in a pure language.
Different monads provide different effects, such as state and error handling.
Many monads even provide useful effects that aren't available in most languages, such as nondeterministic searches, readers, and even continuations.
A typical application has a core set of easily testable functions written without monads paired with an outer wrapper that uses a monad to encode the necessary application logic.
These monads are constructed from well-known components.
For example:
* Mutable state is encoded with a function parameter and a return value that have the same type
* Error handling is encoded by having a return type that is similar to {moduleName}`Except`, with constructors for success and failure
* Logging is encoded by pairing the return value with the log
Writing each monad by hand is tedious, however, involving boilerplate definitions of the various type classes.
Each of these components can also be extracted to a definition that modifies some other monad to add an additional effect.
Such a definition is called a _monad transformer_.
A concrete monad can be build from a collection of monad transformers, which enables much more code re-use.
{include 1 FPLean.MonadTransformers.ReaderIO}
{include 1 FPLean.MonadTransformers.Transformers}
{include 1 FPLean.MonadTransformers.Order}
{include 1 FPLean.MonadTransformers.Do}
{include 1 FPLean.MonadTransformers.Conveniences}
{include 1 FPLean.MonadTransformers.Summary} |
fp-lean/book/FPLean/Meta.lean | import VersoManual
namespace FPLean |
fp-lean/book/FPLean/Basic.lean | |
fp-lean/book/FPLean/PropsProofsIndexing.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.Props"
set_option pp.rawOnError true
#doc (Manual) "Interlude: Propositions, Proofs, and Indexing" =>
%%%
tag := "props-proofs-indexing"
number := false
htmlSplit := .never
%%%
Like many languages, Lean uses square brackets for indexing into arrays and lists.
For instance, if {moduleTerm}`woodlandCritters` is defined as follows:
```anchor woodlandCritters
def woodlandCritters : List String :=
["hedgehog", "deer", "snail"]
```
then the individual components can be extracted:
```anchor animals
def hedgehog := woodlandCritters[0]
def deer := woodlandCritters[1]
def snail := woodlandCritters[2]
```
However, attempting to extract the fourth element results in a compile-time error, rather than a run-time error:
```anchor outOfBounds
def oops := woodlandCritters[3]
```
```anchorError outOfBounds
failed to prove index is valid, possible solutions:
- Use `have`-expressions to prove the index is valid
- Use `a[i]!` notation instead, runtime check is performed, and 'Panic' error message is produced if index is not valid
- Use `a[i]?` notation instead, result is an `Option` type
- Use `a[i]'h` notation instead, where `h` is a proof that index is valid
⊢ 3 < woodlandCritters.length
```
This error message is saying Lean tried to automatically mathematically prove that {moduleTerm}`3 < woodlandCritters.length` (i.e. {moduleTerm}`3 < List.length woodlandCritters`), which would mean that the lookup was safe, but that it could not do so.
Out-of-bounds errors are a common class of bugs, and Lean uses its dual nature as a programming language and a theorem prover to rule out as many as possible.
Understanding how this works requires an understanding of three key ideas: propositions, proofs, and tactics.
# Propositions and Proofs
%%%
tag := "propositions-and-proofs"
%%%
A _proposition_ is a statement that can be true or false.
All of the following English sentences are propositions:
* $`1 + 1 = 2`
* Addition is commutative.
* There are infinitely many prime numbers.
* $`1 + 1 = 15`
* Paris is the capital of France.
* Buenos Aires is the capital of South Korea.
* All birds can fly.
On the other hand, nonsense statements are not propositions.
Despite being grammatical, none of the following are propositions:
* 1 + green = ice cream
* All capital cities are prime numbers.
* At least one gorg is a fleep.
Propositions come in two varieties: those that are purely mathematical, relying only on our definitions of concepts, and those that are facts about the world.
Theorem provers like Lean are concerned with the former category, and have nothing to say about the flight capabilities of penguins or the legal status of cities.
A _proof_ is a convincing argument that a proposition is true.
For mathematical propositions, these arguments make use of the definitions of the concepts that are involved as well as the rules of logical argumentation.
Most proofs are written for people to understand, and leave out many tedious details.
Computer-aided theorem provers like Lean are designed to allow mathematicians to write proofs while omitting many details, and it is the software's responsibility to fill in the missing explicit steps.
These steps can be mechanically checked.
This decreases the likelihood of oversights or mistakes.
In Lean, a program's type describes the ways it can be interacted with.
For instance, a program of type {moduleTerm}`Nat → List String` is a function that takes a {moduleTerm}`Nat` argument and produces a list of strings.
In other words, each type specifies what counts as a program with that type.
In Lean, propositions are in fact types.
They specify what counts as evidence that the statement is true.
The proposition is proved by providing this evidence, which is checked by Lean.
On the other hand, if the proposition is false, then it will be impossible to construct this evidence.
For example, the proposition $`1 + 1 = 2` can be written directly in Lean.
The evidence for this proposition is the constructor {moduleTerm}`rfl`, which is short for _reflexivity_.
In mathematics, a relation is _reflexive_ if every element is related to itself; this is a basic requirement in order to have a sensible notion of equality.
Because {moduleTerm}`1 + 1` computes to {moduleTerm}`2`, they are really the same thing:
```anchor onePlusOneIsTwo
def onePlusOneIsTwo : 1 + 1 = 2 := rfl
```
On the other hand, {moduleTerm}`rfl` does not prove the false proposition $`1 + 1 = 15`:
```anchor onePlusOneIsFifteen
def onePlusOneIsFifteen : 1 + 1 = 15 := rfl
```
```anchorError onePlusOneIsFifteen
Type mismatch
rfl
has type
?m.16 = ?m.16
but is expected to have type
1 + 1 = 15
```
This error message indicates that {moduleTerm}`rfl` can prove that two expressions are equal when both sides of the equality statement are already the same number.
Because {moduleTerm}`1 + 1` evaluates directly to {moduleTerm}`2`, they are considered to be the same, which allows {moduleTerm}`onePlusOneIsTwo` to be accepted.
Just as {moduleTerm}`Type` describes types such as {moduleTerm}`Nat`, {moduleTerm}`String`, and {moduleTerm}`List (Nat × String × (Int → Float))` that represent data structures and functions, {moduleTerm}`Prop` describes propositions.
When a proposition has been proven, it is called a _theorem_.
In Lean, it is conventional to declare theorems with the {kw}`theorem` keyword instead of {kw}`def`.
This helps readers see which declarations are intended to be read as mathematical proofs, and which are definitions.
Generally speaking, with a proof, what matters is that there is evidence that a proposition is true, but it's not particularly important _which_ evidence was provided.
With definitions, on the other hand, it matters very much which particular value is selected—after all, a definition of addition that always returns {anchorTerm SomeNats}`0` is clearly wrong.
Because the details of a proof don't matter for later proofs, using the {kw}`theorem` keyword enables greater parallelism in the Lean compiler.
The prior example could be rewritten as follows:
```anchor onePlusOneIsTwoProp
def OnePlusOneIsTwo : Prop := 1 + 1 = 2
theorem onePlusOneIsTwo : OnePlusOneIsTwo := rfl
```
# Tactics
%%%
tag := "tactics"
%%%
Proofs are normally written using _tactics_, rather than by providing evidence directly.
Tactics are small programs that construct evidence for a proposition.
These programs run in a _proof state_ that tracks the statement that is to be proved (called the _goal_) along with the assumptions that are available to prove it.
Running a tactic on a goal results in a new proof state that contains new goals.
The proof is complete when all goals have been proven.
To write a proof with tactics, begin the definition with {kw}`by`.
Writing {kw}`by` puts Lean into tactic mode until the end of the next indented block.
While in tactic mode, Lean provides ongoing feedback about the current proof state.
Written with tactics, {anchorTerm onePlusOneIsTwoTactics}`onePlusOneIsTwo` is still quite short:
```anchor onePlusOneIsTwoTactics
theorem onePlusOneIsTwo : 1 + 1 = 2 := by
decide
```
The {tactic}`decide` tactic invokes a _decision procedure_, which is a program that can check whether a statement is true or false, returning a suitable proof in either case.
It is primarily used when working with concrete values like {anchorTerm SomeNats}`1` and {anchorTerm SomeNats}`2`.
The other important tactics in this book are {tactic}`simp`, short for “simplify,” and {tactic}`grind`, which can automatically prove many theorems.
Tactics are useful for a number of reasons:
1. Many proofs are complicated and tedious when written out down to the smallest detail, and tactics can automate these uninteresting parts.
2. Proofs written with tactics are easier to maintain over time, because flexible automation can paper over small changes to definitions.
3. Because a single tactic can prove many different theorems, Lean can use tactics behind the scenes to free users from writing proofs by hand. For instance, an array lookup requires a proof that the index is in bounds, and a tactic can typically construct that proof without the user needing to worry about it.
Behind the scenes, indexing notation uses a tactic to prove that the user's lookup operation is safe.
This tactic takes many facts about arithmetic into account, combining them with any locally-known facts to attempt to prove that the index is in bounds.
The {tactic}`simp` tactic is a workhorse of Lean proofs.
It rewrites the goal to as simple a form as possible.
In many cases, this rewriting simplifies the statement so much that it can be automatically proved.
Behind the scenes, a detailed formal proof is constructed, but using {tactic}`simp` hides this complexity.
Like {tactic}`decide`, the {tactic}`grind` tactic is used to finish proofs.
It uses a collection of techniques from SMT solvers that can prove a wide variety of theorems.
Unlike {tactic}`simp`, {tactic}`grind` can never make progress towards a proof without completing it entirely; it either succeeds fully or fails.
The {tactic}`grind` tactic is very powerful, customizable, and extensible; due to this power and flexibility, its output when it fails to prove a theorem contains a lot of information that can help trained Lean users diagnose the reason for the failure.
This can be overwhelming in the beginning, so this chapter uses only {tactic}`decide` and {tactic}`simp`.
# Connectives
%%%
tag := "connectives"
%%%
The basic building blocks of logic, such as “and”, “or”, “true”, “false”, and “not”, are called {deftech}_logical connectives_.
Each connective defines what counts as evidence of its truth.
For example, to prove a statement “_A_ and _B_”, one must prove both _A_ and _B_.
This means that evidence for “_A_ and _B_” is a pair that contains both evidence for _A_ and evidence for _B_.
Similarly, evidence for “_A_ or _B_” consists of either evidence for _A_ or evidence for _B_.
In particular, most of these connectives are defined like datatypes, and they have constructors.
If {anchorTerm AndProp}`A` and {anchorTerm AndProp}`B` are propositions, then “{anchorTerm AndProp}`A` and {anchorTerm AndProp}`B`” (written {anchorTerm AndProp}`A ∧ B`) is a proposition.
Evidence for {anchorTerm AndProp}`A ∧ B` consists of the constructor {anchorTerm AndIntro}`And.intro`, which has the type {anchorTerm AndIntro}`A → B → A ∧ B`.
Replacing {anchorTerm AndIntro}`A` and {anchorTerm AndIntro}`B` with concrete propositions, it is possible to prove {anchorTerm AndIntroEx}`1 + 1 = 2 ∧ "Str".append "ing" = "String"` with {anchorTerm AndIntroEx}`And.intro rfl rfl`.
Of course, {tactic}`decide` is also powerful enough to find this proof:
```anchor AndIntroExTac
theorem addAndAppend : 1 + 1 = 2 ∧ "Str".append "ing" = "String" := by
decide
```
Similarly, “{anchorTerm OrProp}`A` or {anchorTerm OrProp}`B`” (written {anchorTerm OrProp}`A ∨ B`) has two constructors, because a proof of “{anchorTerm OrProp}`A` or {anchorTerm OrProp}`B`” requires only that one of the two underlying propositions be true.
There are two constructors: {anchorTerm OrIntro1}`Or.inl`, with type {anchorTerm OrIntro1}`A → A ∨ B`, and {anchorTerm OrIntro2}`Or.inr`, with type {anchorTerm OrIntro2}`B → A ∨ B`.
Implication (if {anchorTerm impliesDef}`A` then {anchorTerm impliesDef}`B`) is represented using functions.
In particular, a function that transforms evidence for {anchorTerm impliesDef}`A` into evidence for {anchorTerm impliesDef}`B` is itself evidence that {anchorTerm impliesDef}`A` implies {anchorTerm impliesDef}`B`.
This is different from the usual description of implication, in which {anchorTerm impliesDef}`A → B` is shorthand for {anchorTerm impliesDef}`¬A ∨ B`, but the two formulations are equivalent.
Because evidence for an “and” is a constructor, it can be used with pattern matching.
For instance, a proof that {anchorTerm andImpliesOr}`A` and {anchorTerm andImpliesOr}`B` implies {anchorTerm andImpliesOr}`A` or {anchorTerm andImpliesOr}`B` is a function that pulls the evidence of {anchorTerm andImpliesOr}`A` (or of {anchorTerm andImpliesOr}`B`) out of the evidence for {anchorTerm andImpliesOr}`A` and {anchorTerm andImpliesOr}`B`, and then uses this evidence to produce evidence of {anchorTerm andImpliesOr}`A` or {anchorTerm andImpliesOr}`B`:
```anchor andImpliesOr
theorem andImpliesOr : A ∧ B → A ∨ B :=
fun andEvidence =>
match andEvidence with
| And.intro a b => Or.inl a
```
:::table +header
*
- Connective
- Lean Syntax
- Evidence
*
- True
- {anchorName connectiveTable}`True`
- {anchorTerm connectiveTable}`True.intro : True`
*
- False
- {anchorName connectiveTable}`False`
- No evidence
*
- {anchorName connectiveTable}`A` and {anchorName connectiveTable}`B`
- {anchorTerm connectiveTable}`A ∧ B`
- {anchorTerm connectiveTable}`And.intro : A → B → A ∧ B`
*
- {anchorName connectiveTable}`A` or {anchorName connectiveTable}`B`
- {anchorTerm connectiveTable}`A ∨ B`
- Either {anchorTerm connectiveTable}`Or.inl : A → A ∨ B` or {anchorTerm connectiveTable}`Or.inr : B → A ∨ B`
*
- {anchorName connectiveTable}`A` implies {anchorName connectiveTable}`B`
- {anchorTerm connectiveTable}`A → B`
- A function that transforms evidence of {anchorName connectiveTable}`A` into evidence of {anchorName connectiveTable}`B`
*
- not {anchorName connectiveTable}`A`
- {anchorTerm connectiveTable}`¬A`
- A function that would transform evidence of {anchorName connectiveTable}`A` into evidence of {anchorName connectiveTable}`False`
:::
The {tactic}`decide` tactic can prove theorems that use these connectives.
For example:
```anchor connectivesD
theorem onePlusOneOrLessThan : 1 + 1 = 2 ∨ 3 < 5 := by decide
theorem notTwoEqualFive : ¬(1 + 1 = 5) := by decide
theorem trueIsTrue : True := by decide
theorem trueOrFalse : True ∨ False := by decide
theorem falseImpliesTrue : False → True := by decide
```
# Evidence as Arguments
%%%
tag := "evidence-passing"
%%%
In some cases, safely indexing into a list requires that the list have some minimum size, but the list itself is a variable rather than a concrete value.
For this lookup to be safe, there must be some evidence that the list is long enough.
One of the easiest ways to make indexing safe is to have the function that performs a lookup into a data structure take the required evidence of safety as an argument.
For instance, a function that returns the third entry in a list is not generally safe because lists might contain zero, one, or two entries:
```anchor thirdErr
def third (xs : List α) : α := xs[2]
```
```anchorError thirdErr
failed to prove index is valid, possible solutions:
- Use `have`-expressions to prove the index is valid
- Use `a[i]!` notation instead, runtime check is performed, and 'Panic' error message is produced if index is not valid
- Use `a[i]?` notation instead, result is an `Option` type
- Use `a[i]'h` notation instead, where `h` is a proof that index is valid
α : Type ?u.5379
xs : List α
⊢ 2 < xs.length
```
However, the obligation to show that the list has at least three entries can be imposed on the caller by adding an argument that consists of evidence that the indexing operation is safe:
```anchor third
def third (xs : List α) (ok : xs.length > 2) : α := xs[2]
```
In this example, {anchorTerm third}`xs.length > 2` is not a program that checks _whether_ {anchorTerm third}`xs` has more than 2 entries.
It is a proposition that could be true or false, and the argument {anchorTerm third}`ok` must be evidence that it is true.
When the function is called on a concrete list, its length is known.
In these cases, {anchorTerm thirdCritters}`by decide` can construct the evidence automatically:
```anchor thirdCritters
#eval third woodlandCritters (by decide)
```
```anchorInfo thirdCritters
"snail"
```
# Indexing Without Evidence
%%%
tag := "indexing-without-evidence"
%%%
In cases where it's not practical to prove that an indexing operation is in bounds, there are other alternatives.
Adding a question mark results in an {anchorName thirdOption}`Option`, where the result is {anchorName OptionNames}`some` if the index is in bounds, and {anchorName OptionNames}`none` otherwise.
For example:
```anchor thirdOption
def thirdOption (xs : List α) : Option α := xs[2]?
```
```anchor thirdOptionCritters
#eval thirdOption woodlandCritters
```
```anchorInfo thirdOptionCritters
some "snail"
```
```anchor thirdOptionTwo
#eval thirdOption ["only", "two"]
```
```anchorInfo thirdOptionTwo
none
```
:::paragraph
There is also a version that crashes the program when the index is out of bounds, rather than returning an {moduleTerm}`Option`:
```anchor crittersBang
#eval woodlandCritters[1]!
```
```anchorInfo crittersBang
"deer"
```
:::
# Messages You May Meet
%%%
tag := "props-proofs-indexing-messages"
%%%
In addition to proving that a statement is true, the {anchorTerm thirdRabbitErr}`decide` tactic can also prove that it is false.
When asked to prove that a one-element list has more than two elements, it returns an error that indicates that the statement is indeed false:
```anchor thirdRabbitErr
#eval third ["rabbit"] (by decide)
```
```anchorError thirdRabbitErr
Tactic `decide` proved that the proposition
["rabbit"].length > 2
is false
```
The {tactic}`simp` and {tactic}`decide` tactics do not automatically unfold definitions with {kw}`def`.
Attempting to prove {anchorTerm onePlusOneIsStillTwo}`OnePlusOneIsTwo` using {anchorTerm onePlusOneIsStillTwo}`simp` fails:
```anchor onePlusOneIsStillTwo
theorem onePlusOneIsStillTwo : OnePlusOneIsTwo := by simp
```
The error messages simply states that it could do nothing, because without unfolding {anchorTerm onePlusOneIsStillTwo}`OnePlusOneIsTwo`, no progress can be made:
```anchorError onePlusOneIsStillTwo
`simp` made no progress
```
Using {anchorTerm onePlusOneIsStillTwo2}`decide` also fails:
```anchor onePlusOneIsStillTwo2
theorem onePlusOneIsStillTwo : OnePlusOneIsTwo := by decide
```
This is also due to it not unfolding {anchorName onePlusOneIsStillTwo2}`OnePlusOneIsTwo`:
```anchorError onePlusOneIsStillTwo2
failed to synthesize
Decidable OnePlusOneIsTwo
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
```
Defining {anchorName onePlusOneIsStillTwo}`OnePlusOneIsTwo` with {ref "abbrev-vs-def"}[{kw}`abbrev` fixes the problem] by marking the definition for unfolding.
In addition to the error that occurs when Lean is unable to find compile-time evidence that an indexing operation is safe, polymorphic functions that use unsafe indexing may produce the following message:
```anchor unsafeThird
def unsafeThird (xs : List α) : α := xs[2]!
```
```anchorError unsafeThird
failed to synthesize
Inhabited α
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
```
This is due to a technical restriction that is part of keeping Lean usable as both a logic for proving theorems and a programming language.
In particular, only programs whose types contain at least one value are allowed to crash.
This is because a proposition in Lean is a kind of type that classifies evidence of its truth.
False propositions have no such evidence.
If a program with an empty type could crash, then that crashing program could be used as a kind of fake evidence for a false proposition.
Internally, Lean contains a table of types that are known to have at least one value.
This error is saying that some arbitrary type {anchorTerm unsafeThird}`α` is not necessarily in that table.
The next chapter describes how to add to this table, and how to successfully write functions like {anchorTerm unsafeThird}`unsafeThird`.
Adding whitespace between a list and the brackets used for lookup can cause another message:
```anchor extraSpace
#eval woodlandCritters [1]
```
```anchorError extraSpace
Function expected at
woodlandCritters
but this term has type
List String
Note: Expected a function because this term is being applied to the argument
[1]
```
Adding a space causes Lean to treat the expression as a function application, and the index as a list that contains a single number.
This error message results from having Lean attempt to treat {anchorTerm woodlandCritters}`woodlandCritters` as a function.
## Exercises
%%%
tag := "props-proofs-indexing-exercises"
%%%
* Prove the following theorems using {anchorTerm exercises}`rfl`: {anchorTerm exercises}`2 + 3 = 5`, {anchorTerm exercises}`15 - 8 = 7`, {anchorTerm exercises}`"Hello, ".append "world" = "Hello, world"`. What happens if {anchorTerm exercises}`rfl` is used to prove {anchorTerm exercises}`5 < 18`? Why?
* Prove the following theorems using {anchorTerm exercises}`by decide`: {anchorTerm exercises}`2 + 3 = 5`, {anchorTerm exercises}`15 - 8 = 7`, {anchorTerm exercises}`"Hello, ".append "world" = "Hello, world"`, {anchorTerm exercises}`5 < 18`.
* Write a function that looks up the fifth entry in a list. Pass the evidence that this lookup is safe as an argument to the function. |
fp-lean/book/FPLean/FunctorApplicativeMonad.lean | import VersoManual
import FPLean.Examples
import FPLean.FunctorApplicativeMonad.Inheritance
import FPLean.FunctorApplicativeMonad.Applicative
import FPLean.FunctorApplicativeMonad.ApplicativeContract
import FPLean.FunctorApplicativeMonad.Alternative
import FPLean.FunctorApplicativeMonad.Universes
import FPLean.FunctorApplicativeMonad.Complete
import FPLean.FunctorApplicativeMonad.Summary
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.FunctorApplicativeMonad"
#doc (Manual) "Functors, Applicative Functors, and Monads" =>
{anchorTerm FunctorPair}`Functor` and {moduleName}`Monad` both describe operations for types that are still waiting for a type argument.
One way to understand them is that {anchorTerm FunctorPair}`Functor` describes containers in which the contained data can be transformed, and {moduleName}`Monad` describes an encoding of programs with side effects.
This understanding is incomplete, however.
After all, {moduleName}`Option` has instances for both {moduleName}`Functor` and {moduleName}`Monad`, and simultaneously represents an optional value _and_ a computation that might fail to return a value.
From the perspective of data structures, {anchorName AlternativeOption}`Option` is a bit like a nullable type or like a list that can contain at most one entry.
From the perspective of control structures, {anchorName AlternativeOption}`Option` represents a computation that might terminate early without a result.
Typically, programs that use the {anchorName FunctorValidate}`Functor` instance are easiest to think of as using {anchorName AlternativeOption}`Option` as a data structure, while programs that use the {anchorName MonadExtends}`Monad` instance are easiest to think of as using {anchorName AlternativeOption}`Option` to allow early failure, but learning to use both of these perspectives fluently is an important part of becoming proficient at functional programming.
There is a deeper relationship between functors and monads.
It turns out that _every monad is a functor_.
Another way to say this is that the monad abstraction is more powerful than the functor abstraction, because not every functor is a monad.
Furthermore, there is an additional intermediate abstraction, called _applicative functors_, that has enough power to write many interesting programs and yet permits libraries that cannot use the {anchorName MonadExtends}`Monad` interface.
The type class {anchorName ApplicativeValidate}`Applicative` provides the overloadable operations of applicative functors.
Every monad is an applicative functor, and every applicative functor is a functor, but the converses do not hold.
{include 1 FPLean.FunctorApplicativeMonad.Inheritance}
{include 1 FPLean.FunctorApplicativeMonad.Applicative}
{include 1 FPLean.FunctorApplicativeMonad.ApplicativeContract}
{include 1 FPLean.FunctorApplicativeMonad.Alternative}
{include 1 FPLean.FunctorApplicativeMonad.Universes}
{include 1 FPLean.FunctorApplicativeMonad.Complete}
{include 1 FPLean.FunctorApplicativeMonad.Summary} |
fp-lean/book/FPLean/Acks.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.TODO"
#doc (Manual) "Acknowledgments" =>
%%%
number := false
%%%
This free online book was made possible by the generous support of Microsoft Research, who paid for it to be written and given away.
During the process of writing, they made the expertise of the Lean development team available to both answer my questions and make Lean easier to use.
In particular, Leonardo de Moura initiated the project and helped me get started, Chris Lovett set up the CI and deployment automation and provided great feedback as a test reader, Gabriel Ebner provided technical reviews, Sarah Smith kept the administrative side working well, and Vanessa Rodriguez helped me diagnose a tricky interaction between the source-code highlighting library and certain versions of Safari on iOS.
Writing this book has taken up many hours outside of normal working hours.
My wife Ellie Thrane Christiansen has taken on a larger than usual share of running the family, and this book could not exist if she had not done so.
An extra day of work each week has not been easy for my family—thank you for your patience and support while I was writing.
The online community surrounding Lean provided enthusiastic support for the project, both technical and emotional.
In particular, Sebastian Ullrich provided key help when I was learning Lean's metaprogramming system in order to write the supporting code that allowed the text of error messages to be both checked in CI and easily included in the book itself.
Within hours of posting a new revision, excited readers would be finding mistakes, providing suggestions, and showering me with kindness.
In particular, I'd like to thank Arien Malec, Asta Halkjær From, Bulhwi Cha, Craig Stuntz, Daniel Fabian, Evgenia Karunus, eyelash, Floris van Doorn, František Silváši, Henrik Böving, Ian Young, Jeremy Salwen, Jireh Loreaux, Kevin Buzzard, Lars Ericson, Liu Yuxi, Mac Malone, Malcolm Langfield, Mario Carneiro, Newell Jensen, Patrick Massot, Paul Chisholm, Pietro Monticone, Tomas Puverle, Yaël Dillies, Zhiyuan Bao, and Zyad Hassan for their many suggestions, both stylistic and technical. |
fp-lean/book/FPLean/TypeClasses.lean | import VersoManual
import FPLean.Examples
import FPLean.TypeClasses.Pos
import FPLean.TypeClasses.Polymorphism
import FPLean.TypeClasses.OutParams
import FPLean.TypeClasses.Indexing
import FPLean.TypeClasses.Coercions
import FPLean.TypeClasses.Conveniences
import FPLean.TypeClasses.StandardClasses
import FPLean.TypeClasses.Summary
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.Classes"
set_option pp.rawOnError true
#doc (Manual) "Overloading and Type Classes" =>
%%%
tag := "type-classes"
%%%
In many languages, the built-in datatypes get special treatment.
For example, in C and Java, {lit}`+` can be used to add {c}`float`s and {c}`int`s, but not arbitrary-precision numbers from a third-party library.
Similarly, numeric literals can be used directly for the built-in types, but not for user-defined number types.
Other languages provide an {deftech}_overloading_ mechanism for operators, where the same operator can be given a meaning for a new type.
In these languages, such as C++ and C#, a wide variety of built-in operators can be overloaded, and the compiler uses the type checker to select a particular implementation.
In addition to numeric literals and operators, many languages allow overloading of functions or methods.
In C++, Java, C# and Kotlin, multiple implementations of a method are allowed, with differing numbers and types of arguments.
The compiler uses the number of arguments and their types to determine which overload was intended.
Function and operator overloading has a key limitation: polymorphic functions can't restrict their type arguments to types for which a given overload exists.
For example, an overloaded method might be defined for strings, byte arrays, and file pointers, but there's no way to write a second method that works for any of these.
Instead, this second method must itself be overloaded for each type that has an overload of the original method, resulting in many boilerplate definitions instead of a single polymorphic definition.
Another consequence of this restriction is that some operators (such as equality in Java) end up being defined for _every_ combination of arguments, even when it is not necessarily sensible to do so.
If programmers are not very careful, this can lead to programs that crash at runtime or silently compute an incorrect result.
Lean implements overloading using a mechanism called {deftech}_type classes_, pioneered in Haskell, that allows overloading of operators, functions, and literals in a manner that works well with polymorphism.
A type class describes a collection of overloadable operations.
To overload these operations for a new type, an _instance_ is created that contains an implementation of each operation for the new type.
For example, a type class named {anchorName chapterIntro}`Add` describes types that allow addition, and an instance of {anchorTerm chapterIntro}`Add` for {anchorTerm chapterIntro}`Nat` provides an implementation of addition for {anchorTerm chapterIntro}`Nat`.
The terms _class_ and _instance_ can be confusing for those who are used to object-oriented languages, because they are not closely related to classes and instances in object-oriented languages.
However, they do share common roots: in everyday language, the term “class” refers to a group that shares some common attributes.
While classes in object-oriented programming certainly describe groups of objects with common attributes, the term additionally refers to a specific mechanism in a programming language for describing such a group.
Type classes are also a means of describing types that share common attributes (namely, implementations of certain operations), but they don't really have anything else in common with classes as found in object-oriented programming.
A Lean type class is much more analogous to a Java or C# _interface_.
Both type classes and interfaces describe a conceptually related set of operations that are implemented for a type or collection of types.
Similarly, an instance of a type class is akin to the code in a Java or C# class that is prescribed by the implemented interfaces, rather than an instance of a Java or C# class.
Unlike Java or C#'s interfaces, types can be given instances for type classes that the author of the type does not have access to.
In this way, they are very similar to Rust traits.
{include 1 FPLean.TypeClasses.Pos}
{include 1 FPLean.TypeClasses.Polymorphism}
{include 1 FPLean.TypeClasses.OutParams}
{include 1 FPLean.TypeClasses.Indexing}
{include 1 FPLean.TypeClasses.StandardClasses}
{include 1 FPLean.TypeClasses.Coercions}
{include 1 FPLean.TypeClasses.Conveniences}
{include 1 FPLean.TypeClasses.Summary} |
fp-lean/book/FPLean/Examples.lean | import SubVerso.Examples
import Lean.Data.NameMap
import Lean.DocString.Syntax
import VersoManual
import FPLean.Examples.Commands
import FPLean.Examples.OtherLanguages
open Lean (NameMap MessageSeverity)
open Lean.Doc.Syntax
namespace FPLean
open Verso Doc Elab Genre.Manual ArgParse Code Highlighted WebAssets Output Html Log Code External
open SubVerso.Highlighting
open SubVerso.Examples.Messages
open Lean
open Std
open InlineLean (FileType)
private def oneCodeStr [Monad m] [MonadError m] (inlines : Array (TSyntax `inline)) : m StrLit := do
let #[code] := inlines
| (if inlines.size == 0 then (throwError ·) else (throwErrorAt (mkNullNode inlines) ·)) "Expected one code element"
let `(inline|code($code)) := code
| throwErrorAt code "Expected a code element"
return code
private def oneCodeStr? [Monad m] [MonadError m] [MonadLog m] [AddMessageContext m] [MonadOptions m]
(inlines : Array (TSyntax `inline)) : m (Option StrLit) := do
let #[code] := inlines
| if inlines.size == 0 then
logError "Expected a code element"
else
logErrorAt (mkNullNode inlines) "Expected one code element"
return none
let `(inline|code($code)) := code
| logErrorAt code "Expected a code element"
return none
return some code
private def oneCodeName [Monad m] [MonadError m] (inlines : Array (TSyntax `inline)) : m Ident := do
let code ← oneCodeStr inlines
let str := code.getString
let name := if str.contains '.' then str.toName else Name.str .anonymous str
return mkIdentFrom code name
section
open Elab Term
variable {m} [Monad m] [MonadReaderOf Term.Context m] [MonadLiftT TermElabM m] [MonadLiftT MetaM m] [MonadMCtx m] [MonadError m] [MonadLCtx m]
structure ExampleModule (module : Name) where
partial def currentExampleModule : m Name := do
let ctx ← readThe Term.Context
let mut theName : Name := .anonymous
for (_, fv) in ctx.sectionFVars do
let t ← Meta.inferType fv >>= instantiateExprMVars
let t ← Meta.whnf t
if t.isAppOfArity' ``ExampleModule 1 then
let nameExpr := t.getArg! 0
let nameExpr ← Meta.reduceAll nameExpr
theName ← nameFromExpr nameExpr
if theName.isAnonymous then throwError "No default example module provided with 'example_module'"
else return theName
where
nameFromExpr expr : m Name := do
match_expr expr with
| Name.anonymous => return .anonymous
| Name.str x y =>
if let .lit (.strVal s) := y then
return .str (← nameFromExpr x) s
else throwError "Not a string literal: {y}"
| Name.num x y =>
if let .lit (.natVal n) := y then
return .num (← nameFromExpr x) n
else throwError "Not a natural number literal: {y}"
| _ => throwError "Failed to reify expression as name: {expr}"
macro "example_module" name:ident : command => `(variable (_ : ExampleModule $(quote name.getId)))
def mod (ref : Syntax) : ArgParse m Ident :=
(.positional `module .ident <* .done) <|>
(.lift "Default example module" (mkIdentFrom ref <$> currentExampleModule) <* .done)
def modAndName (ref : Syntax) : ArgParse m (Ident × Ident) :=
((·, ·) <$> .positional `module .ident <*> .positional `decl .ident <* .done) <|>
((·, ·) <$> .lift "Default example module" (mkIdentFrom ref <$> currentExampleModule) <*> .positional `decl .ident <* .done)
def modAndNameAndSev [MonadLiftT CoreM m] (ref : Syntax) : ArgParse m (Ident × Ident × MessageSeverity) :=
((·, ·, ·) <$> .positional `module .ident <*> .positional `decl .ident <*> .positional `severity .messageSeverity) <|>
((·, ·, ·) <$> .lift "Default example module" (mkIdentFrom ref <$> currentExampleModule) <*> .positional `decl .ident <*> .positional `severity .messageSeverity)
def modAndNameThen (ref : Syntax) (more : ArgParse m α) : ArgParse m (Ident × Ident × α) :=
((·, ·, ·) <$> .positional `module .ident <*> .positional `decl .ident <*> more <* .done) <|>
((·, ·, ·) <$> .lift "Default example module" (mkIdentFrom ref <$> currentExampleModule) <*> .positional `decl .ident <*> more <* .done)
def modAndThen (ref : Syntax) (more : ArgParse m α) : ArgParse m (Ident × α) :=
((·, ·) <$> .positional `module .ident <*> more <* .done) <|>
((·, ·) <$> .lift "Default example module" (mkIdentFrom ref <$> currentExampleModule) <*> more <* .done)
end
block_extension Block.creativeCommons where
traverse _ _ _ := pure none
toTeX := none
toHtml :=
open Verso.Output.Html in
some <| fun _ _ _ _ _ =>
pure {{
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/">
<img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png" />
</a>
<br />
"This work is licensed under a "
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/">
"Creative Commons Attribution 4.0 International License"
</a>"."
}}
@[block_command]
def creativeCommons : BlockCommandOf Unit
| () => do
``(Block.other (Block.creativeCommons) #[])
def evalStepsStyle := r#"
div.paragraph > .eval-steps:not(:first-child), div.paragraph > .eval-steps:not(:first-child) > * {
margin-top: 0.5rem;
}
div.paragraph > .eval-steps:not(:last-child), div.paragraph > .eval-steps:not(:last-child) > * {
margin-bottom: 0.5rem;
}
.eval-steps .hl.lean.block {
margin-top: 0.25em;
margin-bottom: 0.25em;
}
.eval-steps .hl.lean.block:not(:last-child)::after {
content: "⟹";
display: block;
margin-left: 1em;
font-size: 175%;
}
"#
block_extension Block.leanEvalSteps (steps : Array Highlighted) via withHighlighting where
data := ToJson.toJson steps
traverse _ _ _ := pure none
toTeX := none
extraCss := [evalStepsStyle]
toHtml :=
open Verso.Output.Html in
some <| fun _ _ _ data _ => do
match FromJson.fromJson? data with
| .error err =>
HtmlT.logError <| "Couldn't deserialize Lean code block while rendering HTML: " ++ err
pure .empty
| .ok (steps : Array Highlighted) =>
let i := steps.map (·.indentation) |>.toList |>.min? |>.getD 0
return {{
<div class="eval-steps">
{{← steps.mapM (·.deIndent i |>.blockHtml "examples" (g := Verso.Genre.Manual))}}
</div>
}}
block_extension Block.leanEqReason where
traverse _ _ _ := pure none
toTeX := none
toHtml :=
open Verso.Output.Html in
some <| fun _ goB _ _ contents => do
return {{
<div class="reason">
{{ ← contents.mapM goB }}
</div>
}}
extraCss := [
r#"
.eq-steps .hl.lean.block {
background-color: #f6f7f6;
padding: 1rem;
margin-top: 0.25rem;
margin-bottom: 0.25rem;
}
.eq-steps .reason {
font-style: italic;
margin-left: 2.5em;
display: flex;
}
.eq-steps .reason::before {
content: "={";
font-family: var(--verso-code-font-family);
font-style: normal;
font-weight: 600;
margin-right: 0.5em;
align-self: center;
}
.eq-steps .reason > p {
margin: 0;
max-width: 25em;
align-self: center;
}
.eq-steps .reason::after {
content: "}=";
font-family: var(--verso-code-font-family);
font-style: normal;
font-weight: 600;
margin-left: 1em;
align-self: center;
}
"#
]
def eqStepsStyle := r#"
div.paragraph > .eq-steps:not(:first-child) {
margin-top: 0.5rem;
}
div.paragraph > .eq-steps:not(:last-child) {
margin-bottom: 0.5rem;
}
"#
block_extension Block.leanEqSteps where
traverse _ _ _ := pure none
toTeX := none
extraCss := [eqStepsStyle]
toHtml :=
open Verso.Output.Html in
some <| fun _ goB _ _ contents => do
return {{
<div class="eq-steps">
{{ ← contents.mapM goB }}
</div>
}}
private def getClass : MessageSeverity → String
| .error => "error"
| .information => "information"
| .warning => "warning"
block_extension Block.leanOutput (severity : MessageSeverity) (message : String) (summarize : Bool := false) via withHighlighting where
data := ToJson.toJson (severity, message, summarize)
traverse _ _ _ := do
pure none
toTeX :=
some <| fun _ go _ _ content => do
pure <| .seq <| ← content.mapM fun b => do
pure <| .seq #[← go b, .raw "\n"]
toHtml :=
open Verso.Output.Html in
some <| fun _ _ _ data _ => do
match FromJson.fromJson? data with
| .error err =>
HtmlT.logError <| "Couldn't deserialize Lean code while rendering HTML: " ++ err
pure .empty
| .ok ((sev, txt, summarize) : MessageSeverity × String × Bool) =>
let wrap html :=
if summarize then {{<details><summary>"Expand..."</summary>{{html}}</details>}}
else html
pure <| wrap {{<div class={{getClass sev}}><pre>{{txt}}</pre></div>}}
@[role_expander kw]
def kw : RoleExpander
| args, inls => do
ArgParse.done.run args
let kw ← oneCodeStr inls
let hl : Highlighted := .token ⟨.keyword none none none, kw.getString⟩ -- TODO kw xref
return #[← ``(Inline.other (Inline.lean $(quote hl) {}) #[Inline.code $(quote kw.getString)])]
structure OutputInlineConfig where
module : Ident
severity : Option MessageSeverity
plain : Bool := true
section
variable [Monad m] [MonadError m] [MonadLiftT CoreM m] [MonadReaderOf Elab.Term.Context m] [MonadLiftT MetaM m] [MonadMCtx m]
def OutputInlineConfig.parse : ArgParse m OutputInlineConfig :=
(OutputInlineConfig.mk <$>
.lift "Default example module" (do return mkIdentFrom (← getRef) (← currentExampleModule)) <*>
(some <$> .positional `severity .messageSeverity <|> pure none) <*>
.namedD `plain .bool true <* .done) <|>
(OutputInlineConfig.mk <$>
.positional `module .ident <*>
(some <$> .positional `severity .messageSeverity <|> pure none) <*>
.namedD `plain .bool true <* .done)
end
private inductive SplitCtxF where
| tactics : Array (Highlighted.Goal Highlighted) → Nat → Nat → SplitCtxF
| span : Array Highlighted.Message → SplitCtxF
private def SplitCtxF.wrap (hl : Highlighted) : SplitCtxF → Highlighted
| .tactics g s e => .tactics g s e hl
| .span xs => .span (xs.map (fun m => (m.1, m.2))) hl
private structure SplitCtx where
contents : Array (Highlighted × SplitCtxF) := #[]
deriving Inhabited
private def SplitCtx.push (ctx : SplitCtx) (current : Highlighted) (info : SplitCtxF) : SplitCtx where
contents := ctx.contents.push (current, info)
private def SplitCtx.pop (ctx : SplitCtx) : SplitCtx where
contents := ctx.contents.pop
private def SplitCtx.close (ctx : SplitCtx) (current : Highlighted) : Highlighted × SplitCtx :=
match ctx.contents.back? with
| none => panic! s!"Popping empty context around '{current.toString}'"
| some (left, f) => (left ++ f.wrap current, ctx.pop)
private def SplitCtx.split (ctx : SplitCtx) (current : Highlighted) : Highlighted × SplitCtx where
fst := ctx.contents.foldr (init := current) fun (left, f) curr => left ++ f.wrap curr
snd := { contents := ctx.contents.map (.empty, ·.2) }
def splitHighlighted (p : String → Bool) (hl : Highlighted) : Array Highlighted := Id.run do
let mut todo := [some hl]
let mut out := #[]
let mut ctx : SplitCtx := {}
let mut current : Highlighted := .empty
repeat
match todo with
| [] =>
out := out.push current
break
| none :: hs =>
todo := hs
let (c, ctx') := ctx.split current
current := c
ctx := ctx'
| some (.seq xs) :: hs =>
todo := xs.toList.map some ++ hs
| some this@(.token ⟨_, t⟩) :: hs =>
todo := hs
if p t then
out := out.push current
current := .empty
else
current := current ++ this
| some this@(.text ..) :: hs
| some this@(.unparsed ..) :: hs
| some this@(.point ..) :: hs =>
todo := hs
current := current ++ this
| some (.span msgs x) :: hs =>
todo := some x :: none :: hs
ctx := ctx.push current (.span <| msgs.map fun x => ⟨x.1, x.2⟩)
current := .empty
| some (.tactics gs b e x) :: hs =>
todo := some x :: none :: hs
ctx := ctx.push current (.tactics gs b e)
current := .empty
return out
structure EvalStepContext extends CodeContext where
step : WithSyntax Nat
instance [Monad m] [MonadOptions m] [MonadError m] [MonadLiftT CoreM m] : FromArgs EvalStepContext m where
fromArgs := (fun x y => EvalStepContext.mk y x) <$> .positional' `step <*> fromArgs
private def replicateString (n : Nat) (c : Char) : String :=
n.fold (init := "") fun _ _ s => s.push c
private theorem replicateString_length {n c} : (replicateString n c).length = n := by
simp [replicateString]
induction n <;> simp [Nat.fold, *]
private def quoteCode (str : String) : String := Id.run do
let str := if str.startsWith "`" || str.endsWith "`" then " " ++ str ++ " " else str
let mut n := 1
let mut run := none
let mut iter := str.startPos
while h : iter ≠ str.endPos do
let c := iter.get h
iter := iter.next h
if c == '`' then
run := some (run.getD 0 + 1)
else if let some k := run then
if k > n then n := k
run := none
let delim := replicateString n '`'
return delim ++ str ++ delim
@[role_expander moduleEvalStep]
def moduleEvalStep : RoleExpander
| args, inls => do
let {project, module := moduleName, anchor?, step, showProofStates := _, defSite := _} ← parseThe EvalStepContext args
let code? ← oneCodeStr? inls
let modStr := moduleName.getId.toString
let items ← loadModuleContent project modStr
let highlighted := Highlighted.seq (items.map (·.code))
let fragment ←
if let some anchor := anchor? then
try
let {anchors, ..} ← anchored project moduleName anchor
if let some hl := anchors[anchor.getId.toString]? then
pure hl
else
logErrorAt anchor "Anchor not found"
for x in anchors.keys do
Suggestion.saveSuggestion anchor x x
return #[← ``(sorryAx _ true)]
catch
| .error refStx e =>
logErrorAt refStx e
return #[← ``(sorryAx _ true)]
| e =>
throw e
else pure highlighted
let steps := splitHighlighted (· == "===>") fragment
if let some step := steps[step.val]? then
if let some code := code? then
_ ← ExpectString.expectString "step" code step.toString.trimAscii.copy
return #[← ``(Inline.other (Inline.lean $(quote step) {}) #[])]
else
let stepStr := step.toString
Lean.logError m!"No expected term provided for `{stepStr}`."
if let `(inline|role{$_ $_*} [%$tok1 $contents* ]%$tok2) := (← getRef) then
let stx :=
if tok1.getHeadInfo matches .original .. && tok2.getHeadInfo matches .original .. then
mkNullNode #[tok1, tok2]
else mkNullNode contents
Suggestion.saveSuggestion stx (ExpectString.abbreviateString (quoteCode stepStr)) (quoteCode stepStr)
return #[← ``(sorryAx _ true)]
else
let ok := steps.mapIdx fun i s => ({suggestion := toString i, postInfo? := some s.toString})
let h ← MessageData.hint "Use a step in the range 0–{steps.size}" ok (ref? := some step.syntax)
logErrorAt step.syntax m!"Step not found - only {steps.size} are available{h}"
return #[← ``(sorryAx _ true)]
macro_rules
| `(inline|role{anchorEvalStep $a:arg_val $n:arg_val $arg*}[$i*]) =>
`(inline|role{moduleEvalStep $n:arg_val $arg* anchor := $a }[$i*])
private def editCodeBlock [Monad m] [MonadFileMap m] (stx : Syntax) (newContents : String) : m (Option String) := do
let txt ← getFileMap
let some rng := stx.getRange?
| pure none
let { start := {line := l1, ..}, .. } := txt.utf8RangeToLspRange rng
let line1 := (txt.lineStart (l1 + 1)).extract txt.source (txt.lineStart (l1 + 2))
if line1.startsWith "```" then
return some s!"{delims}{line1.dropWhile (· == '`') |>.trimAscii.copy}\n{withNl newContents}{delims}"
else
return none
where
delims : String := Id.run do
let mut n := 3
let mut run := none
let mut iter := newContents.startPos
while h : iter ≠ newContents.endPos do
let c := iter.get h
iter := iter.next h
if c == '`' then
run := some (run.getD 0 + 1)
else if let some k := run then
if k > n then n := k
run := none
if let some k := run then
if k > n then n := k
n.fold (fun _ _ s => s.push '`') ""
@[code_block_expander moduleEvalStep]
def moduleEvalStepBlock : CodeBlockExpander
| args, code => do
let {project, module := moduleName, anchor?, step, showProofStates := _, defSite := _} ← parseThe EvalStepContext args
withAnchored project moduleName anchor? fun fragment => do
let steps := splitHighlighted (· == "===>") fragment
if let some step := steps[step.val]? then
_ ← ExpectString.expectString "step" code (withNl step.toString.trimAscii.copy)
return #[← ``(Block.other (Block.lean $(quote step) {}) #[])]
else
let ok := steps.mapIdx fun i s => ({suggestion := toString i, postInfo? := some s.toString})
let h ← MessageData.hint "Use a step in the range 0–{steps.size}" ok (ref? := some step.syntax)
logErrorAt step.syntax m!"Step not found - only {steps.size} are available{h}"
return #[← ``(sorryAx _ true)]
macro_rules
| `(block|```%$t1 anchorEvalStep $a:arg_val $n:arg_val $arg* | $s ```%$t2) =>
`(block|```%$t1 moduleEvalStep $n:arg_val $arg* anchor := $a | $s ```%$t2)
@[code_block_expander moduleEvalSteps]
def moduleEvalSteps : CodeBlockExpander
| args, str => do
let {project, module := moduleName, anchor?, showProofStates := _, defSite := _} ← parseThe CodeContext args
withAnchored project moduleName anchor? fun fragment => do
_ ← ExpectString.expectString "steps" str fragment.toString
let steps := splitHighlighted (· == "===>") fragment
return #[← ``(Block.other (Block.leanEvalSteps $(quote steps)) #[])]
macro_rules
| `(block|```%$t1 anchorEvalSteps $a:arg_val $arg* | $s ```%$t2) =>
`(block|```%$t1 moduleEvalSteps $arg* anchor := $a | $s ```%$t2)
@[code_block_expander moduleEqSteps]
def moduleEqSteps : CodeBlockExpander
| args, str => do
let {project, module := moduleName, anchor?, showProofStates := _, defSite := _} ← parseThe CodeContext args
withAnchored project moduleName anchor? fun fragment => do
_ ← ExpectString.expectString "steps" str fragment.toString
let steps := splitHighlighted (· ∈ ["={", "}="]) fragment
let steps ← steps.mapM fun hl => do
if let some ((.token ⟨.docComment, txt⟩), _) := hl.firstToken then
let txt := txt.trimAscii |>.dropPrefix "/--" |>.dropSuffix "-/" |>.trimAscii |>.copy
if let some ⟨#[.p txts]⟩ := MD4Lean.parse txt then
let mut out : Array Term := #[]
for txt in txts do
match txt with
| .normal s => out := out.push (← ``(Inline.text $(quote s)))
| .softbr s => out := out.push (← ``(Inline.linebreak $(quote s)))
| .code c =>
let code := String.join c.toList
if let some hl := hl.matchingExpr? code <|> fragment.matchingExpr? code then
out := out.push (← ``(Inline.other (Inline.lean $(quote hl) {}) #[]))
else
logWarning m!"Failed to match `{code}` in `{hl.toString}`"
out := out.push (← ``(Inline.code $(quote code)))
| o => logWarning m!"Unsupported Markdown: {repr o}"
``(Block.other Block.leanEqReason #[Block.para #[$(out),*] ])
else
``(Block.other Block.leanEqReason #[Block.para #[Inline.text $(quote txt) ] ])
else ``(ExternalCode.leanBlock $(quote hl) {})
let steps : Array Term := steps.map quote
return #[← ``(Block.other Block.leanEqSteps #[$steps,*])]
macro_rules
| `(block|```%$t1 anchorEqSteps $a:arg_val $arg* | $s ```%$t2) =>
`(block|```%$t1 moduleEqSteps $arg* anchor := $a | $s ```%$t2)
def withNl (s : String) : String := if s.endsWith "\n" then s else s ++ "\n"
structure ContainerConfig where
container : Ident
dir : StrLit
structure CommandsConfig extends ContainerConfig where
«show» : Bool
structure CommandConfig extends ContainerConfig where
«show» : Option StrLit := none
viaShell : Bool := false
section
variable [Monad m] [MonadError m] [MonadLiftT CoreM m]
instance : FromArgs ContainerConfig m where
fromArgs := ContainerConfig.mk <$> .positional `container .ident <*> .positional `dir .strLit
instance : FromArgs CommandConfig m where
fromArgs := CommandConfig.mk <$> fromArgs <*> .named `show .strLit true <*> .namedD `shell .bool false
instance : FromArgs CommandsConfig m where
fromArgs := CommandsConfig.mk <$> fromArgs <*> .namedD `show .bool true
end
inline_extension Inline.shellCommand (command : String) where
traverse _ _ _ := pure none
data := .str command
toTeX := none
toHtml := some fun _ _ data _ => do
let .str command := data
| HtmlT.logError s!"Failed to deserialize commands:\n{data}"
return .empty
let piece := {{ <code class="command">{{command}}</code> }}
pure {{
<span class="shell-command inline">{{piece}}</span>
}}
extraCss := [
r#"
.shell-command {
}
.shell-command.inline > * {
display: inline;
white-space: pre;
}
.shell-command.inline .command::before {
content: "$ ";
font-weight: 600;
}
"#
]
block_extension Block.shellCommand (command : String) (prompt : Option String) where
traverse _ _ _ := pure none
data := .arr #[.str command, prompt.map .str |>.getD .null]
toTeX := none
toHtml := some fun _ _ _ data _ => do
let .arr #[.str command, prompt?] := data
| HtmlT.logError s!"Failed to deserialize commands:\n{data}"
return .empty
let prompt? :=
match prompt? with
| .str p => some p
| _ => none
let piece := {{ <code class="command"><code class="prompt">{{prompt?.getD "$ "}}</code>{{command}}</code> }}
pure {{
<div class="shell-command block">{{piece}}</div>
}}
extraCss := [
r#"
.shell-command {
}
.shell-command.block > * {
display: block;
white-space: pre;
}
.shell-command .command .prompt {
font-weight: 600;
}
div.paragraph > .shell-command:not(:first-child) {
margin-top: 0.5rem;
}
div.paragraph > .shell-command:not(:last-child) {
margin-bottom: 0.5rem;
}
"#
]
@[role_expander command]
def command : RoleExpander
| args, inls => do
let { container, dir, «show», viaShell } ← parseThe CommandConfig args
let cmd ← oneCodeStr inls
let output ← Commands.command container dir.getString cmd (viaShell := viaShell)
unless output.stdout.isEmpty do
logSilentInfo <| "Stdout:\n" ++ output.stdout
unless output.stderr.isEmpty do
logSilentInfo <| "Stderr:\n" ++ output.stderr
let out := «show».getD cmd |>.getString
return #[← ``(Inline.other (Inline.shellCommand $(quote out)) #[Inline.code $(quote out)])]
structure CommandBlockConfig extends CommandConfig where
command : StrLit
prompt : Option StrLit := none
section
variable [Monad m] [MonadError m] [MonadLiftT CoreM m]
def CommandBlockConfig.parse : ArgParse m CommandBlockConfig :=
(fun container dir command «show» prompt viaShell => {container, dir, command, «show», prompt, viaShell}) <$>
.positional `container .ident <*>
.positional `dir .strLit <*>
.positional `command .strLit <*>
.named `show .strLit true <*>
.named `prompt .strLit true <*>
.namedD `shell .bool false
instance : FromArgs CommandBlockConfig m where
fromArgs := CommandBlockConfig.parse
end
@[block_command command]
def commandBlock : BlockCommandOf CommandBlockConfig
| { container, dir, command, «show», prompt, viaShell } => do
let output ← Commands.command container dir.getString command (viaShell := viaShell)
unless output.stdout.isEmpty do
logSilentInfo <| "Stdout:\n" ++ output.stdout
unless output.stderr.isEmpty do
logSilentInfo <| "Stderr:\n" ++ output.stderr
let out := «show».getD command |>.getString
``(Block.other (Block.shellCommand $(quote out) $(quote <| prompt.map (·.getString))) #[Block.code $(quote out)])
instance : Coe StrLit (TSyntax `doc_arg) where
coe stx := ⟨mkNode ``Lean.Doc.Syntax.anon #[mkNode ``Lean.Doc.Syntax.arg_str #[stx.raw]]⟩
macro_rules
| `(block|```command $args* | $s```) => `(block|command{command $args* $s})
@[role_expander commandOut]
def commandOut : RoleExpander
| args, inls => do
let container ← ArgParse.run (.positional `container .ident) args
let cmd ← oneCodeStr inls
let output ← Commands.commandOut container cmd
logSilentInfo output
return #[← ``(Inline.code $(quote output.trimAscii.copy))]
@[code_block_expander commandOut]
def commandOutCodeBlock : CodeBlockExpander
| args, outStr => do
let (container, command) ← ArgParse.run ((·, ·) <$> .positional `container .ident <*> .positional `command .strLit) args
let output ← Commands.commandOut container command
_ ← ExpectString.expectString "command output" outStr (withNl output) (useLine := fun l => !l.trimAscii.isEmpty) (preEq := (·.trimAscii.copy))
logSilentInfo output
return #[← ``(Block.code $(quote output))]
block_extension Block.shellCommands (segments : Array (String × Bool)) where
traverse _ _ _ := pure none
data := toJson segments
toTeX := none
toHtml := some fun _ _ _ data _ => do
let .ok (segments : Array (String × Bool)) := fromJson? data
| HtmlT.logError s!"Failed to deserialize commands:\n{data}"
return .empty
let pieces := segments.map fun (s, cmd) =>
{{ <code class={{if cmd then "command" else "output"}}>{{s}}</code> }}
pure {{
<div class="shell-commands">{{pieces}}</div>
}}
extraCss := [
r#"
.shell-commands {
}
.shell-commands > * {
display: block;
white-space: pre;
}
.shell-commands .command::before {
content: "$ ";
font-weight: 600;
}
div.paragraph > .shell-commands:not(:first-child) {
margin-top: 0.5rem;
}
div.paragraph > .shell-commands:not(:last-child) {
margin-bottom: 0.5rem;
}
"#
]
private inductive CommandSpec where
| run (cmd : String) (show? : Option String)
| quote (cmd : String)
| out (text : String)
@[code_block_expander commands]
def commands : CodeBlockExpander
| args, str => do
let {container, dir, «show»} ← parseThe CommandsConfig args
let specStr := str.getString
let mut commands : Array CommandSpec := #[]
let mut quoted := false
for line in specStr.splitOn "\n" do
if line.startsWith "$$" then
commands := commands.push (.quote (line.drop 2 |>.trimAscii |>.copy))
quoted := true
else if line.startsWith "$" then
let line := line.drop 1 |>.trimAscii
quoted := false
if line.contains '#' then
let cmd := line.takeWhile (· ≠ '#')
let rest := (line.drop (cmd.positions.count + 1)).trimAscii.copy
commands := commands.push (.run cmd.trimAscii.copy (some rest))
else
commands := commands.push (.run line.copy none)
else if quoted then
commands := commands.push (.out line.trimAsciiEnd.copy)
let mut out := #[]
let mut outStr := ""
for cmdSpec in commands do
match cmdSpec with
| .quote command =>
out := out.push (command, true)
outStr := outStr ++ s!"$$ {command}\n"
| .run command show? =>
if let some toShow := show? then
out := out.push (toShow, true)
outStr := outStr ++ s!"$ {command} # {toShow}\n"
else
out := out.push (command, true)
outStr := outStr ++ s!"$ {command}\n"
let output ← Commands.command container dir.getString (Syntax.mkStrLit command (info := str.raw.getHeadInfo)) (viaShell := true)
unless output.stdout.isEmpty do
out := out.push (output.stdout, false)
outStr := outStr ++ withNl output.stdout
unless output.stderr.isEmpty do
out := out.push (output.stderr, false)
outStr := outStr ++ withNl output.stderr
| .out txt =>
out := out.push (txt, false)
outStr := outStr ++ withNl txt
unless str.getString.trimAscii.isEmpty && outStr.trimAscii.isEmpty do
_ ← ExpectString.expectString "commands" str outStr (preEq := (·.trimAscii.copy))
if «show» then
pure #[← ``(Block.other (Block.shellCommands $(quote out)) #[])]
else pure #[]
@[code_block_expander file]
def file : CodeBlockExpander
| args, expectedContentsStr => do
let (container, file, show?) ← ArgParse.run ((·, ·, ·) <$> .positional `container .ident <*> .positional `file .strLit <*> (some <$> .positional `show .strLit <|> pure none)) args
let show? := show?.map (·.getString)
let c ← Commands.requireContainer container
let fn := c.workingDirectory / "examples" / file.getString
let contents ← IO.FS.readFile fn
let _ ← ExpectString.expectString "file" expectedContentsStr (withNl contents)
logSilentInfo contents
return #[← ``(Block.other (InlineLean.Block.exampleFile (FileType.other $(quote (show?.getD (fn.fileName.getD fn.toString))))) #[Block.code $(quote contents)])]
structure PlainFileConfig where
project : StrLit
file : StrLit
show? : Option StrLit
instance [Monad m] [MonadOptions m] [MonadError m] : FromArgs PlainFileConfig m where
fromArgs := PlainFileConfig.mk <$> projectOrDefault <*> .positional' `file <*> (some <$> .positional `show .strLit <|> pure none)
@[code_block_expander plainFile]
def plainFile : CodeBlockExpander
| args, expectedContentsStr => do
let {project := projectDir, file, show?} ← parseThe PlainFileConfig args
let show? := show?.map (·.getString)
let projectDir : System.FilePath := projectDir.getString
let fn := projectDir / file.getString
let contents ← IO.FS.readFile fn
let _ ← ExpectString.expectString "file" expectedContentsStr (withNl contents)
logSilentInfo contents
return #[← ``(Block.other (InlineLean.Block.exampleFile (FileType.other $(quote (show?.getD (fn.fileName.getD fn.toString))))) #[Block.code $(quote contents)])]
private def severityName {m} [Monad m] [MonadEnv m] [MonadResolveName m] [MonadOptions m] [MonadLog m] [AddMessageContext m] : MessageSeverity → m String
| .error => unresolveNameGlobal ``MessageSeverity.error <&> (·.toString)
| .warning => unresolveNameGlobal ``MessageSeverity.warning <&> (·.toString)
| .information => unresolveNameGlobal ``MessageSeverity.information <&> (·.toString)
deriving instance Repr for MessageSeverity
private def severityHint (wanted : String) (stx : Syntax) : DocElabM MessageData := do
if stx.getHeadInfo matches .original .. then
MessageData.hint m!"Use '{wanted}'" #[wanted] (ref? := some stx)
else pure m!""
open Lean.Meta.Hint in
@[role_expander moduleOutText]
def moduleOutText : RoleExpander
| args, inls => withTraceNode `Elab.Verso (fun _ => pure m!"moduleOutText") <| do
let str? ← oneCodeStr? inls
let {project, module := moduleName, anchor?, severity, showProofStates := _, defSite := _, expandTraces, onlyTrace} ← parseThe MessageContext args
if onlyTrace.isSome then throwError "Unsupported option: `onlyTrace`"
withAnchored project moduleName anchor? fun hl => do
let infos := allInfo hl
if let some str := str? then
let mut strings := #[]
for (msg, _) in infos do
let s := msg.toString (expandTraces := expandTraces)
strings := strings.push s
if messagesMatch s str.getString then
if msg.severity.toSeverity == severity.1 then
return #[← ``(Inline.text $(quote s))]
else
let wanted ← severityName msg.severity.toSeverity
throwError "Mismatched severity. Expected '{repr severity.1}', got '{wanted}'.{← severityHint wanted severity.2}"
let ref :=
if let `(inline|role{ $_ $_* }[ $x ]) := (← getRef) then x.raw else str
let suggs : Array Suggestion := strings.map fun msg => {
suggestion := quoteCode msg.trimAscii.copy
}
let h ←
if suggs.isEmpty then pure m!""
else MessageData.hint "Use one of these." suggs (ref? := some ref)
let err :=
m!"Expected one of:{indentD (m!"\n".joinSep <| infos.toList.map (·.1.toString))}" ++
m!"\nbut got:{indentD str.getString}\n" ++ h
logErrorAt str err
else
let err := m!"Expected one of:{indentD (m!"\n".joinSep <| infos.toList.map (·.1.toString))}"
Lean.logError m!"No expected term provided. {err}"
if let `(inline|role{$_ $_*} [%$tok1 $contents* ]%$tok2) := (← getRef) then
let stx :=
if tok1.getHeadInfo matches .original .. && tok2.getHeadInfo matches .original .. then
mkNullNode #[tok1, tok2]
else mkNullNode contents
for (msg, _) in infos do
let msg := msg.toString.trimAscii.copy
Suggestion.saveSuggestion stx (quoteCode <| ExpectString.abbreviateString msg) (quoteCode msg)
return #[← ``(sorryAx _ true)]
where
quoteCode (str : String) : String := Id.run do
let str := if str.startsWith "`" || str.endsWith "`" then " " ++ str ++ " " else str
let mut n := 1
let mut run := none
let mut iter := str.startPos
while h : iter ≠ str.endPos do
let c := iter.get h
iter := iter.next h
if c == '`' then
run := some (run.getD 0 + 1)
else if let some k := run then
if k > n then n := k
run := none
let delim := replicateString n '`'
return delim ++ str ++ delim
macro_rules
| `(inline|role{%$rs moduleInfoText $arg*}%$re [%$s $str* ]%$e) =>
`(inline|role{%$rs moduleOutText MessageSeverity.information $arg*}%$re [%$s $str* ]%$e)
| `(inline|role{%$rs moduleErrorText $arg*}%$re [%$s $str* ]%$e) =>
`(inline|role{%$rs moduleOutText MessageSeverity.error $arg*}%$re [%$s $str* ]%$e)
| `(inline|role{%$rs moduleWarningText $arg*}%$re [%$s $str* ]%$e) =>
`(inline|role{%$rs moduleOutText MessageSeverity.warning $arg*}%$re [%$s $str* ]%$e)
| `(inline|role{%$rs anchorInfoText $a:arg_val $arg*}%$re [%$s $str* ]%$e) =>
`(inline|role{%$rs moduleOutText MessageSeverity.information anchor:=$a $arg*}%$re [%$s $str* ]%$e)
| `(inline|role{%$rs anchorErrorText $a:arg_val $arg*}%$re [%$s $str* ]%$e) =>
`(inline|role{%$rs moduleOutText MessageSeverity.error anchor:=$a $arg*}%$re [%$s $str* ]%$e)
| `(inline|role{%$rs anchorWarningText $a:arg_val $arg*}%$re [%$s $str* ]%$e) =>
`(inline|role{%$rs moduleOutText MessageSeverity.warning anchor:=$a $arg*}%$re [%$s $str* ]%$e) |
fp-lean/book/FPLean/GettingToKnow.lean | import VersoManual
import FPLean.Examples
import FPLean.GettingToKnow.Evaluating
import FPLean.GettingToKnow.Types
import FPLean.GettingToKnow.FunctionsDefinitions
import FPLean.GettingToKnow.Structures
import FPLean.GettingToKnow.DatatypesPatterns
import FPLean.GettingToKnow.Polymorphism
import FPLean.GettingToKnow.Conveniences
import FPLean.GettingToKnow.Summary
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Hello"
#doc (Manual) "Getting to Know Lean" =>
%%%
tag := "getting-to-know"
%%%
According to tradition, a programming language should be introduced by compiling and running a program that displays {moduleTerm}`"Hello, world!"` on the console.
This simple program ensures that the language tooling is installed correctly and that the programmer is able to run the compiled code.
Since the 1970s, however, programming has changed.
Today, compilers are typically integrated into text editors, and the programming environment offers feedback as the program is written.
Lean is no exception: it implements an extended version of the Language Server Protocol that allows it to communicate with a text editor and provide feedback as the user types.
Languages as varied as Python, Haskell, and JavaScript offer a read-eval-print-loop (REPL), also known as an interactive toplevel or a browser console, in which expressions or statements can be entered.
The language then computes and displays the result of the user's input.
Lean, on the other hand, integrates these features into the interaction with the editor, providing commands that cause the text editor to display feedback integrated into the program text itself.
This chapter provides a short introduction to interacting with Lean in an editor, while {ref "hello-world"}[Hello, World!] describes how to use Lean traditionally from the command line in batch mode.
It is best if you read this book with Lean open in your editor, following along and typing in each example. Please play with the
examples, and see what happens!
{include 1 FPLean.GettingToKnow.Evaluating}
{include 1 FPLean.GettingToKnow.Types}
{include 1 FPLean.GettingToKnow.FunctionsDefinitions}
{include 1 FPLean.GettingToKnow.Structures}
{include 1 FPLean.GettingToKnow.DatatypesPatterns}
{include 1 FPLean.GettingToKnow.Polymorphism}
{include 1 FPLean.GettingToKnow.Conveniences}
{include 1 FPLean.GettingToKnow.Summary} |
fp-lean/book/FPLean/ProgramsProofs.lean | import VersoManual
import FPLean.Examples
import FPLean.ProgramsProofs.TailRecursion
import FPLean.ProgramsProofs.TailRecursionProofs
import FPLean.ProgramsProofs.ArraysTermination
import FPLean.ProgramsProofs.Inequalities
import FPLean.ProgramsProofs.Fin
import FPLean.ProgramsProofs.InsertionSort
import FPLean.ProgramsProofs.SpecialTypes
import FPLean.ProgramsProofs.Summary
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.TODO"
#doc (Manual) "Programming, Proving, and Performance" =>
This chapter is about programming.
Programs need to compute the correct result, but they also need to do so efficiently.
To write efficient functional programs, it's important to know both how to use data structures appropriately and how to think about the time and space needed to run a program.
This chapter is also about proofs.
One of the most important data structures for efficient programming in Lean is the array, but safe use of arrays requires proving that array indices are in bounds.
Furthermore, most interesting algorithms on arrays do not follow the pattern of structural recursion—instead, they iterate over the array.
While these algorithms terminate, Lean will not necessarily be able to automatically check this.
Proofs can be used to demonstrate why a program terminates.
Rewriting programs to make them faster often results in code that is more difficult to understand.
Proofs can also show that two programs always compute the same answers, even if they do so with different algorithms or implementation techniques.
In this way, the slow, straightforward program can serve as a specification for the fast, complicated version.
Combining proofs and programming allows programs to be both safe and efficient.
Proofs allow elision of run-time bounds checks, they render many tests unnecessary, and they provide an extremely high level of confidence in a program without introducing any runtime performance overhead.
However, proving theorems about programs can be time consuming and expensive, so other tools are often more economical.
Interactive theorem proving is a deep topic.
This chapter provides only a taste, oriented towards the proofs that come up in practice while programming in Lean.
Most interesting theorems are not closely related to programming.
Please refer to {ref "next-steps"}[Next Steps] for a list of resources for learning more.
Just as when learning programming, however, there's no substitute for hands-on experience when learning to write proofs—it's time to get started!
{include 1 FPLean.ProgramsProofs.TailRecursion}
{include 1 FPLean.ProgramsProofs.TailRecursionProofs}
{include 1 FPLean.ProgramsProofs.ArraysTermination}
{include 1 FPLean.ProgramsProofs.Inequalities}
{include 1 FPLean.ProgramsProofs.Fin}
{include 1 FPLean.ProgramsProofs.InsertionSort}
{include 1 FPLean.ProgramsProofs.SpecialTypes}
{include 1 FPLean.ProgramsProofs.Summary} |
fp-lean/book/FPLean/HelloWorld.lean | import VersoManual
import FPLean.Examples
import FPLean.HelloWorld.RunningAProgram
import FPLean.HelloWorld.StepByStep
import FPLean.HelloWorld.StartingAProject
import FPLean.HelloWorld.Cat
import FPLean.HelloWorld.Conveniences
import FPLean.HelloWorld.Summary
open Verso.Genre Manual
open Verso Code External
open FPLean
#doc (Manual) "Hello, World!" =>
%%%
tag := "hello-world"
%%%
While Lean has been designed to have a rich interactive environment in which programmers can get quite a lot of feedback from the language without leaving the confines of their favorite text editor, it is also a language in which real programs can be written.
This means that it also has a batch-mode compiler, a build system, a package manager, and all the other tools that are necessary for writing programs.
While the {ref "getting-to-know"}[previous chapter] presented the basics of functional programming in Lean, this chapter explains how to start a programming project, compile it, and run the result.
Programs that run and interact with their environment (e.g. by reading input from standard input or creating files) are difficult to reconcile with the understanding of computation as the evaluation of mathematical expressions.
In addition to a description of the Lean build tools, this chapter also provides a way to think about functional programs that interact with the world.
{include 1 FPLean.HelloWorld.RunningAProgram}
{include 1 FPLean.HelloWorld.StepByStep}
{include 1 FPLean.HelloWorld.StartingAProject}
{include 1 FPLean.HelloWorld.Cat}
{include 1 FPLean.HelloWorld.Conveniences}
{include 1 FPLean.HelloWorld.Summary} |
fp-lean/book/FPLean/DependentTypes.lean | import VersoManual
import FPLean.Examples
import FPLean.DependentTypes.IndexedFamilies
import FPLean.DependentTypes.UniversePattern
import FPLean.DependentTypes.TypedQueries
import FPLean.DependentTypes.IndicesParametersUniverses
import FPLean.DependentTypes.Pitfalls
import FPLean.DependentTypes.Summary
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.DependentTypes"
#doc (Manual) "Programming with Dependent Types" =>
In most statically-typed programming languages, there is a hermetic seal between the world of types and the world of programs.
Types and programs have different grammars and they are used at different times.
Types are typically used at compile time, to check that a program obeys certain invariants.
Programs are used at run time, to actually perform computations.
When the two interact, it is usually in the form of a type-case operator like an “instance-of” check or a casting operator that provides the type checker with information that was otherwise unavailable, to be verified at run time.
In other words, the interaction consists of types being inserted into the world of programs, where they gain some limited run-time meaning.
Lean does not impose this strict separation.
In Lean, programs may compute types and types may contain programs.
Placing programs in types allows their full computational power to be used at compile time, and the ability to return types from functions makes types into first-class participants in the programming process.
_Dependent types_ are types that contain non-type expressions.
A common source of dependent types is a named argument to a function.
For example, the function {anchorName natOrStringThree}`natOrStringThree` returns either a natural number or a string, depending on which {anchorName natOrStringThree}`Bool` it is passed:
```anchor natOrStringThree
def natOrStringThree (b : Bool) : if b then Nat else String :=
match b with
| true => (3 : Nat)
| false => "three"
```
Further examples of dependent types include:
* {ref "polymorphism"}[The introductory section on polymorphism] contains {anchorName posOrNegThree (module:= Examples.Intro)}`posOrNegThree`, in which the function's return type depends on the value of the argument.
* {ref "literal-numbers"}[The {anchorName OfNat (module := Examples.Classes)}`OfNat` type class] depends on the specific natural number literal being used.
* {ref "validated-input"}[The {anchorName CheckedInput (module := Examples.FunctorApplicativeMonad)}`CheckedInput` structure] used in the example of validators depends on the year in which validation occurred.
* {ref "subtypes"}[Subtypes] contain propositions that refer to particular values.
* Essentially all interesting propositions, including those that determine the validity of {ref "props-proofs-indexing"}[array indexing notation], are types that contain values and are thus dependent types.
Dependent types vastly increase the power of a type system.
The flexibility of return types that branch on argument values enables programs to be written that cannot easily be given types in other type systems.
At the same time, dependent types allow a type signature to restrict which values may be returned from a function, enabling strong invariants to be enforced at compile time.
However, programming with dependent types can be quite complex, and it requires a whole set of skills above and beyond functional programming.
Expressive specifications can be complicated to fulfill, and there is a real risk of tying oneself in knots and being unable to complete the program.
On the other hand, this process can lead to new understanding, which can be expressed in a refined type that can be fulfilled.
While this chapter scratches the surface of dependently typed programming, it is a deep topic that deserves an entire book of its own.
{include 1 FPLean.DependentTypes.IndexedFamilies}
{include 1 FPLean.DependentTypes.UniversePattern}
{include 1 FPLean.DependentTypes.TypedQueries}
{include 1 FPLean.DependentTypes.IndicesParametersUniverses}
{include 1 FPLean.DependentTypes.Pitfalls}
{include 1 FPLean.DependentTypes.Summary} |
fp-lean/book/FPLean/HelloWorld/StartingAProject.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples/second-lake/greeting"
set_option verso.exampleModule "Main"
#doc (Manual) "Starting a Project" =>
%%%
tag := "starting-a-project"
%%%
As a program written in Lean becomes more serious, an ahead-of-time compiler-based workflow that results in an executable becomes more attractive.
Like other languages, Lean has tools for building multiple-file packages and managing dependencies.
The standard Lean build tool is called Lake (short for “Lean Make”).
Lake is typically configured using a TOML file that declaratively specifies dependencies and describes what is to be built.
For advanced use cases, Lake can also be configured in Lean itself.
# First steps
%%%
tag := "lake-new"
%%%
To get started with a project that uses Lake, use the command {command lake "first-lake"}`lake new greeting` in a directory that does not already contain a file or directory called {lit}`greeting`.
This creates a directory called {lit}`greeting` that contains the following files:
* {lit}`Main.lean` is the file in which the Lean compiler will look for the {lit}`main` action.
* {lit}`Greeting.lean` and {lit}`Greeting/Basic.lean` are the scaffolding of a support library for the program.
* {lit}`lakefile.toml` contains the configuration that {lit}`lake` needs to build the application.
* {lit}`lean-toolchain` contains an identifier for the specific version of Lean that is used for the project.
Additionally, {lit}`lake new` initializes the project as a Git repository and configures its {lit}`.gitignore` file to ignore intermediate build products.
Typically, the majority of the application logic will be in a collection of libraries for the program, while {lit}`Main.lean` will contain a small wrapper around these pieces that does things like parsing command lines and executing the central application logic.
To create a project in an already-existing directory, run {lit}`lake init` instead of {lit}`lake new`.
By default, the library file {lit}`Greeting/Basic.lean` contains a single definition:
```file lake "first-lake/greeting/Greeting/Basic.lean" "Greeting/Basic.lean"
def hello := "world"
```
The library file {lit}`Greeting.lean` imports {lit}`Greeting/Basic.lean`:
```file lake "first-lake/greeting/Greeting.lean" "Greeting.lean"
-- This module serves as the root of the `Greeting` library.
-- Import modules here that should be built as part of the library.
import Greeting.Basic
```
This means that everything defined in {lit}`Greeting/Basic.lean` is also available to files that import {lit}`Greeting.lean`.
In {kw}`import` statements, dots are interpreted as directories on disk.
The executable source {lit}`Main.lean` contains:
```file lake "first-lake/greeting/Main.lean" "Main.lean"
import Greeting
def main : IO Unit :=
IO.println s!"Hello, {hello}!"
```
Because {lit}`Main.lean` imports {lit}`Greeting.lean` and {lit}`Greeting.lean` imports {lit}`Greeting/Basic.lean`, the definition of {lit}`hello` is available in {lit}`main`.
To build the package, run the command {command lake "first-lake/greeting"}`lake build`.
After a number of build commands scroll by, the resulting binary has been placed in {lit}`.lake/build/bin`.
Running {command lake "first-lake/greeting"}`./.lake/build/bin/greeting` results in {commandOut lake}`./.lake/build/bin/greeting`.
Instead of running the binary directly, the command {lit}`lake exe` can be used to build the binary if necessary and then run it.
Running {command lake "first-lake/greeting"}`lake exe greeting` also results in {commandOut lake}`lake exe greeting`.
# Lakefiles
%%%
tag := "lakefiles"
%%%
A {lit}`lakefile.toml` describes a _package_, which is a coherent collection of Lean code for distribution, analogous to an {lit}`npm` or {lit}`nuget` package or a Rust crate.
A package may contain any number of libraries or executables.
The [documentation for Lake](https://lean-lang.org/doc/reference/latest/find/?domain=Verso.Genre.Manual.section&name=lake-config-toml) describes the available options in a Lake configuration.
The generated {lit}`lakefile.toml` contains the following:
```file lake "first-lake/greeting/lakefile.toml" "lakefile.toml"
name = "greeting"
version = "0.1.0"
defaultTargets = ["greeting"]
[[lean_lib]]
name = "Greeting"
[[lean_exe]]
name = "greeting"
root = "Main"
```
This initial Lake configuration consists of three items:
* _package_ settings, at the top of the file,
* a _library_ declaration, named {lit}`Greeting`, and
* an _executable_, named {lit}`greeting`.
Each Lake configuration file will contain exactly one package, but any number of dependencies, libraries, or executables.
By convention, package and executable names begin with a lowercase letter, while libraries begin with an uppercase letter.
Dependencies are declarations of other Lean packages (either locally or from remote Git repositories)
The items in the Lake configuration file allow things like source file locations, module hierarchies, and compiler flags to be configured.
Generally speaking, however, the defaults are reasonable.
Lake configuration files written in the Lean format may additionally contain _external libraries_, which are libraries not written in Lean to be statically linked with the resulting executable, _custom targets_, which are build targets that don't fit naturally into the library/executable taxonomy, and _scripts_, which are essentially {moduleName}`IO` actions (similar to {moduleName}`main`), but that additionally have access to metadata about the package configuration.
Libraries, executables, and custom targets are all called _targets_.
By default, {lit}`lake build` builds those targets that are specified in the {lit}`defaultTargets` list.
To build a target that is not a default target, specify the target's name as an argument after {lit}`lake build`.
# Libraries and Imports
%%%
tag := "libraries-and-imports"
%%%
A Lean library consists of a hierarchically organized collection of source files from which names can be imported, called _modules_.
By default, a library has a single root file that matches its name.
In this case, the root file for the library {lit}`Greeting` is {lit}`Greeting.lean`.
The first line of {lit}`Main.lean`, which is {moduleTerm}`import Greeting`, makes the contents of {lit}`Greeting.lean` available in {lit}`Main.lean`.
Additional module files may be added to the library by creating a directory called {lit}`Greeting` and placing them inside.
These names can be imported by replacing the directory separator with a dot.
For instance, creating the file {lit}`Greeting/Smile.lean` with the contents:
```file lake "second-lake/greeting/Greeting/Smile.lean" "Greeting/Smile.lean"
def Expression.happy : String := "a big smile"
```
means that {lit}`Main.lean` can use the definition as follows:
```file lake "second-lake/greeting/Main.lean" "Main.lean"
import Greeting
import Greeting.Smile
open Expression
def main : IO Unit :=
IO.println s!"Hello, {hello}, with {happy}!"
```
The module name hierarchy is decoupled from the namespace hierarchy.
In Lean, modules are units of code distribution, while namespaces are units of code organization.
That is, names defined in the module {lit}`Greeting.Smile` are not automatically in a corresponding namespace {lit}`Greeting.Smile`.
In particular, {moduleName (module:=Greeting.Smile) (show:=happy)}`Expression.happy` is in the {lit}`Expression` namespace.
Modules may place names into any namespace they like, and the code that imports them may {kw}`open` the namespace or not.
{kw}`import` is used to make the contents of a source file available, while {kw}`open` makes names from a namespace available in the current context without prefixes.
The line {moduleTerm}`open Expression` makes the name {moduleName (module:=Greeting.Smile)}`Expression.happy` accessible as {moduleName}`happy` in {moduleName}`main`.
Namespaces may also be opened _selectively_, making only some of their names available without explicit prefixes.
This is done by writing the desired names in parentheses.
For example, {moduleTerm (module:=Aux)}`Nat.toFloat` converts a natural number to a {moduleTerm (module:=Aux)}`Float`.
It can be made available as {moduleName (module:=Aux)}`toFloat` using {moduleTerm (module:=Aux)}`open Nat (toFloat)`. |
fp-lean/book/FPLean/HelloWorld/Conveniences.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "FelineLib"
#doc (Manual) "Additional Conveniences" =>
%%%
tag := "hello-world-conveniences"
%%%
# Nested Actions
%%%
tag := "nested-actions"
%%%
:::paragraph
Many of the functions in {lit}`feline` exhibit a repetitive pattern in which an {anchorName dump}`IO` action's result is given a name, and then used immediately and only once.
For instance, in {moduleName}`dump`:
```anchor dump
partial def dump (stream : IO.FS.Stream) : IO Unit := do
let buf ← stream.read bufsize
if buf.isEmpty then
pure ()
else
let stdout ← IO.getStdout
stdout.write buf
dump stream
```
the pattern occurs for {moduleName (anchor:=stdoutBind)}`stdout`:
```anchor stdoutBind
let stdout ← IO.getStdout
stdout.write buf
```
Similarly, {moduleName}`fileStream` contains the following snippet:
```anchor fileExistsBind
let fileExists ← filename.pathExists
if not fileExists then
```
:::
:::paragraph
When Lean is compiling a {moduleTerm}`do` block, expressions that consist of a left arrow immediately under parentheses are lifted to the nearest enclosing {moduleTerm}`do`, and their results are bound to a unique name.
This unique name replaces the origin of the expression.
This means that {moduleName (module := Examples.Cat)}`dump` can also be written as follows:
```anchor dump (module:=Examples.Cat)
partial def dump (stream : IO.FS.Stream) : IO Unit := do
let buf ← stream.read bufsize
if buf.isEmpty then
pure ()
else
(← IO.getStdout).write buf
dump stream
```
This version of {anchorName dump (module := Examples.Cat)}`dump` avoids introducing names that are used only once, which can greatly simplify a program.
{moduleName (module := Examples.Cat)}`IO` actions that Lean lifts from a nested expression context are called _nested actions_.
:::
:::paragraph
{moduleName (module := Examples.Cat)}`fileStream` can be simplified using the same technique:
```anchor fileStream (module := Examples.Cat)
def fileStream (filename : System.FilePath) : IO (Option IO.FS.Stream) := do
if not (← filename.pathExists) then
(← IO.getStderr).putStrLn s!"File not found: {filename}"
pure none
else
let handle ← IO.FS.Handle.mk filename IO.FS.Mode.read
pure (some (IO.FS.Stream.ofHandle handle))
```
In this case, the local name of {anchorName fileStream (module := Examples.Cat)}`handle` could also have been eliminated using nested actions, but the resulting expression would have been long and complicated.
Even though it's often good style to use nested actions, it can still sometimes be helpful to name intermediate results.
:::
It is important to remember, however, that nested actions are only a shorter notation for {moduleName (module := Examples.Cat)}`IO` actions that occur in a surrounding {moduleTerm (module := Examples.Cat)}`do` block.
The side effects that are involved in executing them still occur in the same order, and execution of side effects is not interspersed with the evaluation of expressions.
Therefore, nested actions cannot be lifted from the branches of an {kw}`if`.
For an example of where this might be confusing, consider the following helper definitions that return data after announcing to the world that they have been executed:
```anchor getNumA (module := Examples.Cat)
def getNumA : IO Nat := do
(← IO.getStdout).putStrLn "A"
pure 5
```
```anchor getNumB (module := Examples.Cat)
def getNumB : IO Nat := do
(← IO.getStdout).putStrLn "B"
pure 7
```
These definitions are intended to stand in for more complicated {anchorName getNumB (module:=Examples.Cat)}`IO` code that might validate user input, read a database, or open a file.
A program that prints {moduleTerm (module := Examples.Cat)}`0` when number A is five, or number B otherwise, might be written as follows:
```anchor testEffects (module := Examples.Cat)
def test : IO Unit := do
let a : Nat := if (← getNumA) == 5 then 0 else (← getNumB)
(← IO.getStdout).putStrLn s!"The answer is {a}"
```
This program would be equivalent to:
```anchor testEffectsExpanded (module := Examples.Cat)
def test : IO Unit := do
let x ← getNumA
let y ← getNumB
let a : Nat := if x == 5 then 0 else y
(← IO.getStdout).putStrLn s!"The answer is {a}"
```
which runs {moduleName (module := Examples.Cat)}`getNumB` regardless of whether the result of {moduleName (module := Examples.Cat)}`getNumA` is equal to {moduleTerm (module := Examples.Cat)}`5`.
To prevent this confusion, nested actions are not allowed in an {kw}`if` that is not itself a line in the {moduleTerm (module := Examples.Cat)}`do`, and the following error message results:
```anchorError testEffects (module := Examples.Cat)
invalid use of `(<- ...)`, must be nested inside a 'do' expression
```
# Flexible Layouts for {lit}`do`
%%%
tag := "do-layout-syntax"
%%%
In Lean, {moduleTerm (module := Examples.Cat)}`do` expressions are whitespace-sensitive.
Each {moduleName (module := Examples.Cat)}`IO` action or local binding in the {moduleTerm (module := Examples.Cat)}`do` is expected to start on its own line, and they should all have the same indentation.
Almost all uses of {moduleTerm (module := Examples.Cat)}`do` should be written this way.
In some rare contexts, however, manual control over whitespace and indentation may be necessary, or it may be convenient to have multiple small actions on a single line.
In these cases, newlines can be replaced with a semicolon and indentation can be replaced with curly braces.
For instance, all of the following programs are equivalent:
```anchor helloOne (module := Examples.Cat)
-- This version uses only whitespace-sensitive layout
def main : IO Unit := do
let stdin ← IO.getStdin
let stdout ← IO.getStdout
stdout.putStrLn "How would you like to be addressed?"
let name := (← stdin.getLine).trim
stdout.putStrLn s!"Hello, {name}!"
```
```anchor helloTwo (module := Examples.Cat)
-- This version is as explicit as possible
def main : IO Unit := do {
let stdin ← IO.getStdin;
let stdout ← IO.getStdout;
stdout.putStrLn "How would you like to be addressed?";
let name := (← stdin.getLine).trim;
stdout.putStrLn s!"Hello, {name}!"
}
```
```anchor helloThree (module := Examples.Cat)
-- This version uses a semicolon to put two actions on the same line
def main : IO Unit := do
let stdin ← IO.getStdin; let stdout ← IO.getStdout
stdout.putStrLn "How would you like to be addressed?"
let name := (← stdin.getLine).trim
stdout.putStrLn s!"Hello, {name}!"
```
Idiomatic Lean code uses curly braces with {moduleTerm (module := Examples.Cat)}`do` very rarely.
# Running {lit}`IO` Actions With {kw}`#eval`
%%%
tag := "eval-io"
%%%
Lean's {moduleTerm (module := Examples.Cat)}`#eval` command can be used to execute {moduleName (module := Examples.Cat)}`IO` actions, rather than just evaluating them.
Normally, adding a {moduleTerm (module := Examples.Cat)}`#eval` command to a Lean file causes Lean to evaluate the provided expression, convert the resulting value to a string, and provide that string as a tooltip and in the info window.
Rather than failing because {moduleName (module := Examples.Cat)}`IO` actions can't be converted to strings, {moduleTerm (module := Examples.Cat)}`#eval` executes them, carrying out their side effects.
If the result of execution is the {moduleName (module := Examples.Cat)}`Unit` value {moduleTerm (module := Examples.Cat)}`()`, then no result string is shown, but if it is a type that can be converted to a string, then Lean displays the resulting value.
:::paragraph
This means that, given the prior definitions of {moduleName (module := Examples.HelloWorld)}`countdown` and {moduleName (module := Examples.HelloWorld)}`runActions`,
```anchor evalDoesIO (module := Examples.HelloWorld)
#eval runActions (countdown 3)
```
displays
```anchorInfo evalDoesIO (module := Examples.HelloWorld)
3
2
1
Blast off!
```
:::
This is the output produced by running the {moduleName (module := Examples.HelloWorld)}`IO` action, rather than some opaque representation of the action itself.
In other words, for {moduleName (module := Examples.HelloWorld)}`IO` actions, {moduleTerm (module := Examples.HelloWorld)}`#eval` both _evaluates_ the provided expression and _executes_ the resulting action value.
Quickly testing {moduleName (module := Examples.HelloWorld)}`IO` actions with {moduleTerm (module := Examples.HelloWorld)}`#eval` can be much more convenient that compiling and running whole programs.
However, there are some limitations.
For instance, reading from standard input simply returns empty input.
Additionally, the {moduleName (module := Examples.HelloWorld)}`IO` action is re-executed whenever Lean needs to update the diagnostic information that it provides to users, and this can happen at unpredictable times.
An action that reads and writes files, for instance, may do so unexpectedly. |
fp-lean/book/FPLean/HelloWorld/StepByStep.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "HelloName"
example_module Examples.HelloWorld
#doc (Manual) "Step By Step" =>
%%%
tag := "step-by-step"
%%%
:::paragraph
A {moduleTerm}`do` block can be executed one line at a time.
Start with the program from the prior section:
```anchor block1
let stdin ← IO.getStdin
let stdout ← IO.getStdout
stdout.putStrLn "How would you like to be addressed?"
let input ← stdin.getLine
let name := input.dropRightWhile Char.isWhitespace
stdout.putStrLn s!"Hello, {name}!"
```
:::
# Standard IO
%%%
tag := "stdio"
%%%
:::paragraph
The first line is {anchor line1}`let stdin ← IO.getStdin`, while the remainder is:
```anchor block2
let stdout ← IO.getStdout
stdout.putStrLn "How would you like to be addressed?"
let input ← stdin.getLine
let name := input.dropRightWhile Char.isWhitespace
stdout.putStrLn s!"Hello, {name}!"
```
:::
To execute a {kw}`let` statement that uses a {anchorTerm block2}`←`, start by evaluating the expression to the right of the arrow (in this case, {moduleTerm}`IO.getStdin`).
Because this expression is just a variable, its value is looked up.
The resulting value is a built-in primitive {moduleTerm}`IO` action.
The next step is to execute this {moduleTerm}`IO` action, resulting in a value that represents the standard input stream, which has type {moduleTerm}`IO.FS.Stream`.
Standard input is then associated with the name to the left of the arrow (here {anchorTerm line1}`stdin`) for the remainder of the {moduleTerm}`do` block.
Executing the second line, {anchor line2}`let stdout ← IO.getStdout`, proceeds similarly.
First, the expression {moduleTerm}`IO.getStdout` is evaluated, yielding an {moduleTerm}`IO` action that will return the standard output.
Next, this action is executed, actually returning the standard output.
Finally, this value is associated with the name {anchorTerm line2}`stdout` for the remainder of the {moduleTerm}`do` block.
# Asking a Question
%%%
tag := "asking-a-question"
%%%
:::paragraph
Now that {anchorTerm line1}`stdin` and {anchorTerm line2}`stdout` have been found, the remainder of the block consists of a question and an answer:
```anchor block3
stdout.putStrLn "How would you like to be addressed?"
let input ← stdin.getLine
let name := input.dropRightWhile Char.isWhitespace
stdout.putStrLn s!"Hello, {name}!"
```
:::
The first statement in the block, {anchor line3}`stdout.putStrLn "How would you like to be addressed?"`, consists of an expression.
To execute an expression, it is first evaluated.
In this case, {moduleTerm}`IO.FS.Stream.putStrLn` has type {moduleTerm}`IO.FS.Stream → String → IO Unit`.
This means that it is a function that accepts a stream and a string, returning an {moduleTerm}`IO` action.
The expression uses {ref "behind-the-scenes"}[accessor notation] for a function call.
This function is applied to two arguments: the standard output stream and a string.
The value of the expression is an {moduleTerm}`IO` action that will write the string and a newline character to the output stream.
Having found this value, the next step is to execute it, which causes the string and newline to actually be written to {anchorTerm setup}`stdout`.
Statements that consist only of expressions do not introduce any new variables.
The next statement in the block is {anchor line4}`let input ← stdin.getLine`.
{moduleTerm}`IO.FS.Stream.getLine` has type {moduleTerm}`IO.FS.Stream → IO String`, which means that it is a function from a stream to an {moduleTerm}`IO` action that will return a string.
Once again, this is an example of accessor notation.
This {moduleTerm}`IO` action is executed, and the program waits until the user has typed a complete line of input.
Assume the user writes “{lit}`David`”.
The resulting line ({lit}`"David\n"`) is associated with {anchorTerm block5}`input`, where the escape sequence {lit}`\n` denotes the newline character.
```anchor block5
let name := input.dropRightWhile Char.isWhitespace
stdout.putStrLn s!"Hello, {name}!"
```
:::paragraph
The next line, {anchor line5}`let name := input.dropRightWhile Char.isWhitespace`, is a {kw}`let` statement.
Unlike the other {kw}`let` statements in this program, it uses {anchorTerm block5}`:=` instead of {anchorTerm line4}`←`.
This means that the expression will be evaluated, but the resulting value need not be an {moduleTerm}`IO` action and will not be executed.
In this case, {moduleTerm}`String.dropRightWhile` takes a string and a predicate over characters and returns a new string from which all the characters at the end of the string that satisfy the predicate have been removed.
For example,
```anchorTerm dropBang (module := Examples.HelloWorld)
#eval "Hello!!!".dropRightWhile (· == '!')
```
yields
```anchorInfo dropBang (module := Examples.HelloWorld)
"Hello"
```
and
```anchorTerm dropNonLetter (module := Examples.HelloWorld)
#eval "Hello... ".dropRightWhile (fun c => not (c.isAlphanum))
```
yields
```anchorInfo dropNonLetter (module := Examples.HelloWorld)
"Hello"
```
in which all non-alphanumeric characters have been removed from the right side of the string.
In the current line of the program, whitespace characters (including the newline) are removed from the right side of the input string, resulting in {moduleTerm (module := Examples.HelloWorld)}`"David"`, which is associated with {anchorTerm block5}`name` for the remainder of the block.
:::
# Greeting the User
%%%
tag := "greeting"
%%%
:::paragraph
All that remains to be executed in the {moduleTerm}`do` block is a single statement:
```anchor line6
stdout.putStrLn s!"Hello, {name}!"
```
:::
The string argument to {anchorTerm line6}`putStrLn` is constructed via string interpolation, yielding the string {moduleTerm (module := Examples.HelloWorld)}`"Hello, David!"`.
Because this statement is an expression, it is evaluated to yield an {moduleTerm}`IO` action that will print this string with a newline to standard output.
Once the expression has been evaluated, the resulting {moduleTerm}`IO` action is executed, resulting in the greeting.
# {lit}`IO` Actions as Values
%%%
tag := "actions-as-values"
%%%
In the above description, it can be difficult to see why the distinction between evaluating expressions and executing {moduleTerm}`IO` actions is necessary.
After all, each action is executed immediately after it is produced.
Why not simply carry out the effects during evaluation, as is done in other languages?
The answer is twofold.
First off, separating evaluation from execution means that programs must be explicit about which functions can have side effects.
Because the parts of the program that do not have effects are much more amenable to mathematical reasoning, whether in the heads of programmers or using Lean's facilities for formal proof, this separation can make it easier to avoid bugs.
Secondly, not all {moduleTerm}`IO` actions need be executed at the time that they come into existence.
The ability to mention an action without carrying it out allows ordinary functions to be used as control structures.
:::paragraph
For example, the function {anchorName twice (module:=Examples.HelloWorld)}`twice` takes an {moduleTerm}`IO` action as its argument, returning a new action that will execute the argument action twice.
```anchor twice (module := Examples.HelloWorld)
def twice (action : IO Unit) : IO Unit := do
action
action
```
Executing
```anchorTerm twiceShy (module := Examples.HelloWorld)
twice (IO.println "shy")
```
results in
```anchorInfo twiceShy (module := Examples.HelloWorld)
shy
shy
```
being printed.
This can be generalized to a version that runs the underlying action any number of times:
```anchor nTimes (module := Examples.HelloWorld)
def nTimes (action : IO Unit) : Nat → IO Unit
| 0 => pure ()
| n + 1 => do
action
nTimes action n
```
:::
:::paragraph
In the base case for {moduleTerm (module := Examples.HelloWorld)}`Nat.zero`, the result is {moduleTerm (module := Examples.HelloWorld)}`pure ()`.
The function {moduleTerm (module := Examples.HelloWorld)}`pure` creates an {moduleTerm (module := Examples.HelloWorld)}`IO` action that has no side effects, but returns {moduleTerm (module := Examples.HelloWorld)}`pure`'s argument, which in this case is the constructor for {moduleTerm (module := Examples.HelloWorld)}`Unit`.
As an action that does nothing and returns nothing interesting, {moduleTerm (module := Examples.HelloWorld)}`pure ()` is at the same time utterly boring and very useful.
In the recursive step, a {moduleTerm (module := Examples.HelloWorld)}`do` block is used to create an action that first executes {moduleTerm (module := Examples.HelloWorld)}`action` and then executes the result of the recursive call.
Executing {anchor nTimes3 (module := Examples.HelloWorld)}`#eval nTimes (IO.println "Hello") 3` causes the following output:
```anchorInfo nTimes3 (module := Examples.HelloWorld)
Hello
Hello
Hello
```
:::
:::paragraph
In addition to using functions as control structures, the fact that {moduleTerm (module := Examples.HelloWorld)}`IO` actions are first-class values means that they can be saved in data structures for later execution.
For instance, the function {moduleName (module := Examples.HelloWorld)}`countdown` takes a {moduleTerm (module := Examples.HelloWorld)}`Nat` and returns a list of unexecuted {moduleTerm (module := Examples.HelloWorld)}`IO` actions, one for each {moduleTerm (module := Examples.HelloWorld)}`Nat`:
```anchor countdown (module := Examples.HelloWorld)
def countdown : Nat → List (IO Unit)
| 0 => [IO.println "Blast off!"]
| n + 1 => IO.println s!"{n + 1}" :: countdown n
```
This function has no side effects, and does not print anything.
For example, it can be applied to an argument, and the length of the resulting list of actions can be checked:
```anchor from5 (module := Examples.HelloWorld)
def from5 : List (IO Unit) := countdown 5
```
This list contains six elements (one for each number, plus a {moduleTerm (module := Examples.HelloWorld)}`"Blast off!"` action for zero):
```anchorTerm from5length (module := Examples.HelloWorld)
#eval from5.length
```
```anchorInfo from5length (module := Examples.HelloWorld)
6
```
:::
:::paragraph
The function {moduleTerm (module := Examples.HelloWorld)}`runActions` takes a list of actions and constructs a single action that runs them all in order:
```anchor runActions (module := Examples.HelloWorld)
def runActions : List (IO Unit) → IO Unit
| [] => pure ()
| act :: actions => do
act
runActions actions
```
Its structure is essentially the same as that of {moduleName (module := Examples.HelloWorld)}`nTimes`, except instead of having one action that is executed for each {moduleName (module := Examples.HelloWorld)}`Nat.succ`, the action under each {moduleName (module := Examples.HelloWorld)}`List.cons` is to be executed.
Similarly, {moduleName (module := Examples.HelloWorld)}`runActions` does not itself run the actions.
It creates a new action that will run them, and that action must be placed in a position where it will be executed as a part of {moduleName (module := Examples.HelloWorld)}`main`:
```anchor main (module := Examples.HelloWorld)
def main : IO Unit := runActions from5
```
Running this program results in the following output:
```commands countdownFromFive ""
$ countdown
5
4
3
2
1
Blast off!
```
:::
:::paragraph
What happens when this program is run?
The first step is to evaluate {moduleName (module := Examples.HelloWorld)}`main`. That occurs as follows:
```anchorEvalSteps evalMain (module := Examples.HelloWorld)
main
===>
runActions from5
===>
runActions (countdown 5)
===>
runActions
[IO.println "5",
IO.println "4",
IO.println "3",
IO.println "2",
IO.println "1",
IO.println "Blast off!"]
===>
do IO.println "5"
IO.println "4"
IO.println "3"
IO.println "2"
IO.println "1"
IO.println "Blast off!"
pure ()
```
The resulting {moduleTerm (module := Examples.HelloWorld)}`IO` action is a {moduleTerm (module := Examples.HelloWorld)}`do` block.
Each step of the {moduleTerm (module := Examples.HelloWorld)}`do` block is then executed, one at a time, yielding the expected output.
The final step, {moduleTerm (module := Examples.HelloWorld)}`pure ()`, does not have any effects, and it is only present because the definition of {moduleTerm (module := Examples.HelloWorld)}`runActions` needs a base case.
:::
# Exercise
%%%
tag := "step-by-step-exercise"
%%%
:::paragraph
Step through the execution of the following program on a piece of paper:
```anchor ExMain (module := Examples.HelloWorld)
def main : IO Unit := do
let englishGreeting := IO.println "Hello!"
IO.println "Bonjour!"
englishGreeting
```
While stepping through the program's execution, identify when an expression is being evaluated and when an {moduleTerm (module := Examples.HelloWorld)}`IO` action is being executed.
When executing an {moduleTerm (module := Examples.HelloWorld)}`IO` action results in a side effect, write it down.
After doing this, run the program with Lean and double-check that your predictions about the side effects were correct.
::: |
fp-lean/book/FPLean/HelloWorld/Summary.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.HelloWorld"
#doc (Manual) "Summary" =>
%%%
tag := "hello-world-summary"
%%%
# Evaluation vs Execution
%%%
tag := none
%%%
Side effects are aspects of program execution that go beyond the evaluation of mathematical expressions, such as reading files, throwing exceptions, or triggering industrial machinery.
While most languages allow side effects to occur during evaluation, Lean does not.
Instead, Lean has a type called {moduleName}`IO` that represents _descriptions_ of programs that use side effects.
These descriptions are then executed by the language's run-time system, which invokes the Lean expression evaluator to carry out specific computations.
Values of type {moduleTerm}`IO α` are called _{moduleName}`IO` actions_.
The simplest is {moduleName}`pure`, which returns its argument and has no actual side effects.
{moduleName}`IO` actions can also be understood as functions that take the whole world as an argument and return a new world in which the side effect has occurred.
Behind the scenes, the {moduleName}`IO` library ensures that the world is never duplicated, created, or destroyed.
While this model of side effects cannot actually be implemented, as the whole universe is too big to fit in memory, the real world can be represented by a token that is passed around through the program.
An {moduleName}`IO` action {anchorName MainTypes}`main` is executed when the program starts.
{anchorName MainTypes}`main` can have one of three types:
* {anchorTerm MainTypes}`main : IO Unit` is used for simple programs that cannot read their command-line arguments and always return exit code {anchorTerm MainTypes}`0`,
* {anchorTerm MainTypes}`main : IO UInt32` is used for programs without arguments that may signal success or failure, and
* {anchorTerm MainTypes}`main : List String → IO UInt32` is used for programs that take command-line arguments and signal success or failure.
# {lit}`do` Notation
%%%
tag := none
%%%
The Lean standard library provides a number of basic {moduleName}`IO` actions that represent effects such as reading from and writing to files and interacting with standard input and standard output.
These base {moduleName}`IO` actions are composed into larger {moduleName}`IO` actions using {kw}`do` notation, which is a built-in domain-specific language for writing descriptions of programs with side effects.
A {kw}`do` expression contains a sequence of _statements_, which may be:
* expressions that represent {moduleName}`IO` actions,
* ordinary local definitions with {kw}`let` and {lit}`:=`, where the defined name refers to the value of the provided expression, or
* local definitions with {kw}`let` and {lit}`←`, where the defined name refers to the result of executing the value of the provided expression.
{moduleName}`IO` actions that are written with {kw}`do` are executed one statement at a time.
Furthermore, {kw}`if` and {kw}`match` expressions that occur immediately under a {kw}`do` are implicitly considered to have their own {kw}`do` in each branch.
Inside of a {kw}`do` expression, _nested actions_ are expressions with a left arrow immediately under parentheses.
The Lean compiler implicitly lifts them to the nearest enclosing {kw}`do`, which may be implicitly part of a branch of a {kw}`match` or {kw}`if` expression, and gives them a unique name.
This unique name then replaces the origin site of the nested action.
# Compiling and Running Programs
%%%
tag := none
%%%
A Lean program that consists of a single file with a {moduleName}`main` definition can be run using {lit}`lean --run FILE`.
While this can be a nice way to get started with a simple program, most programs will eventually graduate to a multiple-file project that should be compiled before running.
Lean projects are organized into _packages_, which are collections of libraries and executables together with information about dependencies and a build configuration.
Packages are described using Lake, a Lean build tool.
Use {lit}`lake new` to create a Lake package in a new directory, or {lit}`lake init` to create one in the current directory.
Lake package configuration is another domain-specific language.
Use {lit}`lake build` to build a project.
# Partiality
%%%
tag := none
%%%
One consequence of following the mathematical model of expression evaluation is that every expression must have a value.
This rules out both incomplete pattern matches that fail to cover all constructors of a datatype and programs that can fall into an infinite loop.
Lean ensures that all {kw}`match` expressions cover all cases, and that all recursive functions are either structurally recursive or have an explicit proof of termination.
However, some real programs require the possibility of looping infinitely, because they handle potentially-infinite data, such as POSIX streams.
Lean provides an escape hatch: functions whose definition is marked {kw}`partial` are not required to terminate.
This comes at a cost.
Because types are a first-class part of the Lean language, functions can return types.
Partial functions, however, are not evaluated during type checking, because an infinite loop in a function could cause the type checker to enter an infinite loop.
Furthermore, mathematical proofs are unable to inspect the definitions of partial functions, which means that programs that use them are much less amenable to formal proof. |
fp-lean/book/FPLean/HelloWorld/Cat.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "FelineLib"
example_module Examples.Cat
#doc (Manual) "Worked Example: {lit}`cat`" =>
%%%
tag := "example-cat"
%%%
The standard Unix utility {lit}`cat` takes a number of command-line options, followed by zero or more input files.
If no files are provided, or if one of them is a dash ({lit}`-`), then it takes the standard input as the corresponding input instead of reading a file.
The contents of the inputs are written, one after the other, to the standard output.
If a specified input file does not exist, this is noted on standard error, but {lit}`cat` continues concatenating the remaining inputs.
A non-zero exit code is returned if any of the input files do not exist.
This section describes a simplified version of {lit}`cat`, called {lit}`feline`.
Unlike commonly-used versions of {lit}`cat`, {lit}`feline` has no command-line options for features such as numbering lines, indicating non-printing characters, or displaying help text.
Furthermore, it cannot read more than once from a standard input that's associated with a terminal device.
To get the most benefit from this section, follow along yourself.
It's OK to copy-paste the code examples, but it's even better to type them in by hand.
This makes it easier to learn the mechanical process of typing in code, recovering from mistakes, and interpreting feedback from the compiler.
# Getting Started
%%%
tag := "example-cat-start"
%%%
The first step in implementing {lit}`feline` is to create a package and decide how to organize the code.
In this case, because the program is so simple, all the code will be placed in {lit}`Main.lean`.
The first step is to run {lit}`lake new feline`.
Edit the Lakefile to remove the library, and delete the generated library code and the reference to it from {lit}`Main.lean`.
Once this has been done, {lit}`lakefile.toml` should contain:
```plainFile "feline/1/lakefile.toml"
name = "feline"
version = "0.1.0"
defaultTargets = ["feline"]
[[lean_exe]]
name = "feline"
root = "Main"
```
and {lit}`Main.lean` should contain something like:
```plainFile "feline/1/Main.lean"
def main : IO Unit :=
IO.println s!"Hello, cats!"
```
Alternatively, running {lit}`lake new feline exe` instructs {lit}`lake` to use a template that does not include a library section, making it unnecessary to edit the file.
Ensure that the code can be built by running {command feline1 "feline/1"}`lake build`.
# Concatenating Streams
%%%
tag := "example-cat-streams"
%%%
Now that the basic skeleton of the program has been built, it's time to actually enter the code.
A proper implementation of {lit}`cat` can be used with infinite IO streams, such as {lit}`/dev/random`, which means that it can't read its input into memory before outputting it.
Furthermore, it should not work one character at a time, as this leads to frustratingly slow performance.
Instead, it's better to read contiguous blocks of data all at once, directing the data to the standard output one block at a time.
The first step is to decide how big of a block to read.
For the sake of simplicity, this implementation uses a conservative 20 kilobyte block.
{anchorName bufsize}`USize` is analogous to {c}`size_t` in C—it's an unsigned integer type that is big enough to represent all valid array sizes.
```module (anchor:=bufsize)
def bufsize : USize := 20 * 1024
```
## Streams
%%%
tag := "streams"
%%%
The main work of {lit}`feline` is done by {anchorName dump}`dump`, which reads input one block at a time, dumping the result to standard output, until the end of the input has been reached.
The end of the input is indicated by {anchorName dump}`read` returning an empty byte array:
```module (anchor:=dump)
partial def dump (stream : IO.FS.Stream) : IO Unit := do
let buf ← stream.read bufsize
if buf.isEmpty then
pure ()
else
let stdout ← IO.getStdout
stdout.write buf
dump stream
```
The {anchorName dump}`dump` function is declared {anchorTerm dump}`partial`, because it calls itself recursively on input that is not immediately smaller than an argument.
When a function is declared to be partial, Lean does not require a proof that it terminates.
On the other hand, partial functions are also much less amenable to proofs of correctness, because allowing infinite loops in Lean's logic would make it unsound.
However, there is no way to prove that {anchorName dump}`dump` terminates, because infinite input (such as from {lit}`/dev/random`) would mean that it does not, in fact, terminate.
In cases like this, there is no alternative to declaring the function {anchorTerm dump}`partial`.
The type {anchorName dump}`IO.FS.Stream` represents a POSIX stream.
Behind the scenes, it is represented as a structure that has one field for each POSIX stream operation.
Each operation is represented as an IO action that provides the corresponding operation:
```anchor Stream (module := Examples.Cat)
structure Stream where
flush : IO Unit
read : USize → IO ByteArray
write : ByteArray → IO Unit
getLine : IO String
putStr : String → IO Unit
isTty : BaseIO Bool
```
The type {anchorName Stream (module:=Examples.Cat)}`BaseIO` is a variant of {anchorName Stream (module:=Examples.Cat)}`IO` that rules out run-time errors.
The Lean compiler contains {anchorName Stream (module:=Examples.Cat)}`IO` actions (such as {anchorName dump}`IO.getStdout`, which is called in {anchorName dump}`dump`) to get streams that represent standard input, standard output, and standard error.
These are {anchorName Stream (module:=Examples.Cat)}`IO` actions rather than ordinary definitions because Lean allows these standard POSIX streams to be replaced in a process, which makes it easier to do things like capturing the output from a program into a string by writing a custom {anchorName dump}`IO.FS.Stream`.
The control flow in {anchorName dump}`dump` is essentially a {lit}`while` loop.
When {anchorName dump}`dump` is called, if the stream has reached the end of the file, {anchorTerm dump}`pure ()` terminates the function by returning the constructor for {anchorName dump}`Unit`.
If the stream has not yet reached the end of the file, one block is read, and its contents are written to {anchorName dump}`stdout`, after which {anchorName dump}`dump` calls itself directly.
The recursive calls continue until {anchorTerm dump}`stream.read` returns an empty byte array, which indicates the end of the file.
When an {kw}`if` expression occurs as a statement in a {kw}`do`, as in {anchorName dump}`dump`, each branch of the {kw}`if` is implicitly provided with a {kw}`do`.
In other words, the sequence of steps following the {kw}`else` are treated as a sequence of {anchorName dump}`IO` actions to be executed, just as if they had a {kw}`do` at the beginning.
Names introduced with {kw}`let` in the branches of the {kw}`if` are visible only in their own branches, and are not in scope outside of the {kw}`if`.
There is no danger of running out of stack space while calling {anchorName dump}`dump` because the recursive call happens as the very last step in the function, and its result is returned directly rather than being manipulated or computed with.
This kind of recursion is called _tail recursion_, and it is described in more detail {ref "tail-recursion"}[later in this book].
Because the compiled code does not need to retain any state, the Lean compiler can compile the recursive call to a jump.
If {lit}`feline` only redirected standard input to standard output, then {anchorName dump}`dump` would be sufficient.
However, it also needs to be able to open files that are provided as command-line arguments and emit their contents.
When its argument is the name of a file that exists, {anchorName fileStream}`fileStream` returns a stream that reads the file's contents.
When the argument is not a file, {anchorName fileStream}`fileStream` emits an error and returns {anchorName fileStream}`none`.
```module (anchor:=fileStream)
def fileStream (filename : System.FilePath) : IO (Option IO.FS.Stream) := do
let fileExists ← filename.pathExists
if not fileExists then
let stderr ← IO.getStderr
stderr.putStrLn s!"File not found: {filename}"
pure none
else
let handle ← IO.FS.Handle.mk filename IO.FS.Mode.read
pure (some (IO.FS.Stream.ofHandle handle))
```
Opening a file as a stream takes two steps.
First, a file handle is created by opening the file in read mode.
A Lean file handle tracks an underlying file descriptor.
When there are no references to the file handle value, a finalizer closes the file descriptor.
Second, the file handle is given the same interface as a POSIX stream using {anchorName fileStream}`IO.FS.Stream.ofHandle`, which fills each field of the {anchorName Names}`Stream` structure with the corresponding {anchorName fileStream}`IO` action that works on file handles.
## Handling Input
%%%
tag := "handling-input"
%%%
The main loop of {lit}`feline` is another tail-recursive function, called {anchorName process}`process`.
In order to return a non-zero exit code if any of the inputs could not be read, {anchorName process}`process` takes an argument {anchorName process}`exitCode` that represents the current exit code for the whole program.
Additionally, it takes a list of input files to be processed.
```module (anchor:=process)
def process (exitCode : UInt32) (args : List String) : IO UInt32 := do
match args with
| [] => pure exitCode
| "-" :: args =>
let stdin ← IO.getStdin
dump stdin
process exitCode args
| filename :: args =>
let stream ← fileStream ⟨filename⟩
match stream with
| none =>
process 1 args
| some stream =>
dump stream
process exitCode args
```
Just as with {kw}`if`, each branch of a {kw}`match` that is used as a statement in a {kw}`do` is implicitly provided with its own {kw}`do`.
There are three possibilities.
One is that no more files remain to be processed, in which case {anchorName process}`process` returns the error code unchanged.
Another is that the specified filename is {anchorTerm process}`"-"`, in which case {anchorName process}`process` dumps the contents of the standard input and then processes the remaining filenames.
The final possibility is that an actual filename was specified.
In this case, {anchorName process}`fileStream` is used to attempt to open the file as a POSIX stream.
Its argument is encased in {lit}`⟨ ... ⟩` because a {anchorName Names}`FilePath` is a single-field structure that contains a string.
If the file could not be opened, it is skipped, and the recursive call to {anchorName process}`process` sets the exit code to {anchorTerm process}`1`.
If it could, then it is dumped, and the recursive call to {anchorName process}`process` leaves the exit code unchanged.
{anchorName process}`process` does not need to be marked {kw}`partial` because it is structurally recursive.
Each recursive call is provided with the tail of the input list, and all Lean lists are finite.
Thus, {anchorName process}`process` does not introduce any non-termination.
## Main
%%%
tag := "example-cat-main"
%%%
The final step is to write the {anchorName main}`main` action.
Unlike prior examples, {anchorName main}`main` in {lit}`feline` is a function.
In Lean, {anchorName main}`main` can have one of three types:
* {anchorTerm Names}`main : IO Unit` corresponds to programs that cannot read their command-line arguments and always indicate success with an exit code of {anchorTerm Names}`0`,
* {anchorTerm Names}`main : IO UInt32` corresponds to {c}`int main(void)` in C, for programs without arguments that return exit codes, and
* {anchorTerm Names}`main : List String → IO UInt32` corresponds to {c}`int main(int argc, char **argv)` in C, for programs that take arguments and signal success or failure.
If no arguments were provided, {lit}`feline` should read from standard input as if it were called with a single {anchorTerm main}`"-"` argument.
Otherwise, the arguments should be processed one after the other.
```module (anchor:=main)
def main (args : List String) : IO UInt32 :=
match args with
| [] => process 0 ["-"]
| _ => process 0 args
```
# Meow!
%%%
tag := "example-cat-running"
%%%
:::paragraph
To check whether {lit}`feline` works, the first step is to build it with {command feline2 "feline/2"}`lake build`.
First off, when called without arguments, it should emit what it receives from standard input.
Check that
```command feline2 "feline/2" (shell := true)
echo "It works!" | lake exe feline
```
emits {commandOut feline2}`echo "It works!" | lake exe feline`.
:::
:::paragraph
Secondly, when called with files as arguments, it should print them.
If the file {lit}`test1.txt` contains
```plainFile "feline/2/test1.txt"
It's time to find a warm spot
```
and {lit}`test2.txt` contains
```plainFile "feline/2/test2.txt"
and curl up!
```
then the command
{command feline2 "feline/2" "lake exe feline test1.txt test2.txt"}
should emit
```commandOut feline2 "lake exe feline test1.txt test2.txt"
It's time to find a warm spot
and curl up!
```
:::
Finally, the {lit}`-` argument should be handled appropriately.
```command feline2 "feline/2" (shell := true)
echo "and purr" | lake exe feline test1.txt - test2.txt
```
should yield
```commandOut feline2 "echo \"and purr\" | lake exe feline test1.txt - test2.txt"
It's time to find a warm spot
and purr
and curl up!
```
# Exercise
%%%
tag := "example-cat-exercise"
%%%
Extend {lit}`feline` with support for usage information.
The extended version should accept a command-line argument {lit}`--help` that causes documentation about the available command-line options to be written to standard output. |
fp-lean/book/FPLean/HelloWorld/RunningAProgram.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "HelloName"
example_module Hello
#doc (Manual) "Running a Program" =>
%%%
tag := "running-a-program"
%%%
:::paragraph
The simplest way to run a Lean program is to use the {lit}`--run` option to the Lean executable.
Create a file called {lit}`Hello.lean` and enter the following contents:
```module (module:=Hello)
def main : IO Unit := IO.println "Hello, world!"
```
:::
:::paragraph
Then, from the command line, run:
{command hello "simple-hello" "lean --run Hello.lean"}
The program displays {commandOut hello}`lean --run Hello.lean` and exits.
:::
# Anatomy of a Greeting
%%%
tag := "hello-world-parts"
%%%
When Lean is invoked with the {lit}`--run` option, it invokes the program's {lit}`main` definition.
In programs that do not take command-line arguments, {moduleName (module := Hello)}`main` should have type {moduleTerm}`IO Unit`.
This means that {moduleName (module := Hello)}`main` is not a function, because there are no arrows ({lit}`→`) in its type.
Instead of being a function that has side effects, {moduleTerm}`main` consists of a description of effects to be carried out.
As discussed in {ref "polymorphism"}[the preceding chapter], {moduleTerm}`Unit` is the simplest inductive type.
It has a single constructor called {moduleTerm}`unit` that takes no arguments.
Languages in the C tradition have a notion of a {CSharp}`void` function that does not return any value at all.
In Lean, all functions take an argument and return a value, and the lack of interesting arguments or return values can be signaled by using the {moduleTerm}`Unit` type instead.
If {moduleTerm}`Bool` represents a single bit of information, {moduleTerm}`Unit` represents zero bits of information.
{moduleTerm}`IO α` is the type of a program that, when executed, will either throw an exception or return a value of type {moduleTerm}`α`.
During execution, this program may have side effects.
These programs are referred to as {moduleTerm}`IO` _actions_.
Lean distinguishes between _evaluation_ of expressions, which strictly adheres to the mathematical model of substitution of values for variables and reduction of sub-expressions without side effects, and _execution_ of {anchorTerm sig}`IO` actions, which rely on an external system to interact with the world.
{moduleTerm}`IO.println` is a function from strings to {moduleTerm}`IO` actions that, when executed, write the given string to standard output.
Because this action doesn't read any interesting information from the environment in the process of emitting the string, {moduleTerm}`IO.println` has type {moduleTerm}`String → IO Unit`.
If it did return something interesting, then that would be indicated by the {moduleTerm}`IO` action having a type other than {moduleTerm}`Unit`.
# Functional Programming vs Effects
%%%
tag := "fp-effects"
%%%
Lean's model of computation is based on the evaluation of mathematical expressions, in which variables are given exactly one value that does not change over time.
The result of evaluating an expression does not change, and evaluating the same expression again will always yield the same result.
On the other hand, useful programs must interact with the world.
A program that performs neither input nor output can't ask a user for data, create files on disk, or open network connections.
Lean is written in itself, and the Lean compiler certainly reads files, creates files, and interacts with text editors.
How can a language in which the same expression always yields the same result support programs that read files from disk, when the contents of these files might change over time?
This apparent contradiction can be resolved by thinking a bit differently about side effects.
Imagine a café that sells coffee and sandwiches.
This café has two employees: a cook who fulfills orders, and a worker at the counter who interacts with customers and places order slips.
The cook is a surly person, who really prefers not to have any contact with the world outside, but who is very good at consistently delivering the food and drinks that the café is known for.
In order to do this, however, the cook needs peace and quiet, and can't be disturbed with conversation.
The counter worker is friendly, but completely incompetent in the kitchen.
Customers interact with the counter worker, who delegates all actual cooking to the cook.
If the cook has a question for a customer, such as clarifying an allergy, they send a little note to the counter worker, who interacts with the customer and passes a note back to the cook with the result.
In this analogy, the cook is the Lean language.
When provided with an order, the cook faithfully and consistently delivers what is requested.
The counter worker is the surrounding run-time system that interacts with the world and can accept payments, dispense food, and have conversations with customers.
Working together, the two employees serve all the functions of the restaurant, but their responsibilities are divided, with each performing the tasks that they're best at.
Just as keeping customers away allows the cook to focus on making truly excellent coffee and sandwiches, Lean's lack of side effects allows programs to be used as part of formal mathematical proofs.
It also helps programmers understand the parts of the program in isolation from each other, because there are no hidden state changes that create subtle coupling between components.
The cook's notes represent {moduleTerm}`IO` actions that are produced by evaluating Lean expressions, and the counter worker's replies are the values that are passed back from effects.
This model of side effects is quite similar to how the overall aggregate of the Lean language, its compiler, and its run-time system (RTS) work.
Primitives in the run-time system, written in C, implement all the basic effects.
When running a program, the RTS invokes the {moduleTerm}`main` action, which returns new {moduleTerm}`IO` actions to the RTS for execution.
The RTS executes these actions, delegating to the user's Lean code to carry out computations.
From the internal perspective of Lean, programs are free of side effects, and {moduleTerm}`IO` actions are just descriptions of tasks to be carried out.
From the external perspective of the program's user, there is a layer of side effects that create an interface to the program's core logic.
# Real-World Functional Programming
%%%
tag := "fp-world-passing"
%%%
The other useful way to think about side effects in Lean is by considering {moduleTerm}`IO` actions to be functions that take the entire world as an argument and return a value paired with a new world.
In this case, reading a line of text from standard input _is_ a pure function, because a different world is provided as an argument each time.
Writing a line of text to standard output is a pure function, because the world that the function returns is different from the one that it began with.
Programs do need to be careful to never re-use the world, nor to fail to return a new world—this would amount to time travel or the end of the world, after all.
Careful abstraction boundaries can make this style of programming safe.
If every primitive {moduleTerm}`IO` action accepts one world and returns a new one, and they can only be combined with tools that preserve this invariant, then the problem cannot occur.
This model cannot be implemented.
After all, the entire universe cannot be turned into a Lean value and placed into memory.
However, it is possible to implement a variation of this model with an abstract token that stands for the world.
When the program is started, it is provided with a world token.
This token is then passed on to the IO primitives, and their returned tokens are similarly passed to the next step.
At the end of the program, the token is returned to the operating system.
This model of side effects is a good description of how {moduleTerm}`IO` actions as descriptions of tasks to be carried out by the RTS are represented internally in Lean.
The actual functions that transform the real world are behind an abstraction barrier.
But real programs typically consist of a sequence of effects, rather than just one.
To enable programs to use multiple effects, there is a sub-language of Lean called {kw}`do` notation that allows these primitive {moduleTerm}`IO` actions to be safely composed into a larger, useful program.
# Combining {anchorName all}`IO` Actions
%%%
tag := "combining-io-actions"
%%%
Most useful programs accept input in addition to producing output.
Furthermore, they may take decisions based on input, using the input data as part of a computation.
The following program, called {lit}`HelloName.lean`, asks the user for their name and then greets them:
```module (anchor:=all)
def main : IO Unit := do
let stdin ← IO.getStdin
let stdout ← IO.getStdout
stdout.putStrLn "How would you like to be addressed?"
let input ← stdin.getLine
let name := input.dropRightWhile Char.isWhitespace
stdout.putStrLn s!"Hello, {name}!"
```
In this program, the {anchorName all}`main` action consists of a {kw}`do` block.
This block contains a sequence of _statements_, which can be both local variables (introduced using {kw}`let`) and actions that are to be executed.
Just as SQL can be thought of as a special-purpose language for interacting with databases, the {kw}`do` syntax can be thought of as a special-purpose sub-language within Lean that is dedicated to modeling imperative programs.
{anchorName all}`IO` actions that are built with a {kw}`do` block are executed by executing the statements in order.
This program can be run in the same manner as the prior program:
{command helloName "hello-name" "expect -f ./run" (show := "lean --run HelloName.lean")}
If the user responds with {lit}`David`, a session of interaction with the program reads:
```commandOut helloName "expect -f ./run"
How would you like to be addressed?
David
Hello, David!
```
The type signature line is just like the one for {lit}`Hello.lean`:
```module (anchor:=sig)
def main : IO Unit := do
```
The only difference is that it ends with the keyword {moduleTerm}`do`, which initiates a sequence of commands.
Each indented line following the keyword {kw}`do` is part of the same sequence of commands.
The first two lines, which read:
```module (anchor:=setup)
let stdin ← IO.getStdin
let stdout ← IO.getStdout
```
retrieve the {moduleTerm (anchor := setup)}`stdin` and {moduleTerm (anchor := setup)}`stdout` handles by executing the library actions {moduleTerm (anchor := setup)}`IO.getStdin` and {moduleTerm (anchor := setup)}`IO.getStdout`, respectively.
In a {moduleTerm}`do` block, {moduleTerm}`let` has a slightly different meaning than in an ordinary expression.
Ordinarily, the local definition in a {moduleTerm}`let` can be used in just one expression, which immediately follows the local definition.
In a {moduleTerm}`do` block, local bindings introduced by {moduleTerm}`let` are available in all statements in the remainder of the {moduleTerm}`do` block, rather than just the next one.
Additionally, {moduleTerm}`let` typically connects the name being defined to its definition using {lit}`:=`, while some {moduleTerm}`let` bindings in {moduleTerm}`do` use a left arrow ({lit}`←` or {lit}`<-`) instead.
Using an arrow means that the value of the expression is an {moduleTerm}`IO` action that should be executed, with the result of the action saved in the local variable.
In other words, if the expression to the right of the arrow has type {moduleTerm}`IO α`, then the variable has type {moduleTerm}`α` in the remainder of the {moduleTerm}`do` block.
{moduleTerm (anchor := setup)}`IO.getStdin` and {moduleTerm (anchor := setup)}`IO.getStdout` are {moduleTerm (anchor := sig)}`IO` actions in order to allow {moduleTerm (anchor := setup)}`stdin` and {moduleTerm (anchor := setup)}`stdout` to be locally overridden in a program, which can be convenient.
If they were global variables as in C, then there would be no meaningful way to override them, but {moduleName}`IO` actions can return different values each time they are executed.
The next part of the {moduleTerm}`do` block is responsible for asking the user for their name:
```module (anchor:=question)
stdout.putStrLn "How would you like to be addressed?"
let input ← stdin.getLine
let name := input.dropRightWhile Char.isWhitespace
```
The first line writes the question to {moduleTerm (anchor := setup)}`stdout`, the second line requests input from {moduleTerm (anchor := setup)}`stdin`, and the third line removes the trailing newline (plus any other trailing whitespace) from the input line.
The definition of {moduleTerm (anchor := question)}`name` uses {lit}`:=`, rather than {lit}`←`, because {moduleTerm}`String.dropRightWhile` is an ordinary function on strings, rather than an {moduleTerm (anchor := sig)}`IO` action.
Finally, the last line in the program is:
```module (anchor:=answer)
stdout.putStrLn s!"Hello, {name}!"
```
It uses {ref "string-interpolation"}[string interpolation] to insert the provided name into a greeting string, writing the result to {moduleTerm (anchor := setup)}`stdout`. |
fp-lean/book/FPLean/MonadTransformers/ReaderIO.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "DirTree"
#doc (Manual) "Combining IO and Reader" =>
%%%
tag := "io-reader"
%%%
One case where a reader monad can be useful is when there is some notion of the “current configuration” of the application that is passed through many recursive calls.
An example of such a program is {lit}`tree`, which recursively prints the files in the current directory and its subdirectories, indicating their tree structure using characters.
The version of {lit}`tree` in this chapter, called {lit}`doug` after the mighty Douglas Fir tree that adorns the west coast of North America, provides the option of Unicode box-drawing characters or their ASCII equivalents when indicating directory structure.
For example, the following commands create a directory structure and some empty files in a directory called {lit}`doug-demo`:
```commands doug "doug-demo"
$$ cd doug-demo
$ mkdir -p a/b/c
$ mkdir -p a/d
$ mkdir -p a/e/f
$ touch a/b/hello
$ touch a/d/another-file
$ touch a/e/still-another-file-again
```
Running {lit}`doug` results in the following:
```commands doug "doug-demo"
$ doug
├── doug-demo/
│ ├── a/
│ │ ├── b/
│ │ │ ├── c/
│ │ │ ├── hello
│ │ ├── d/
│ │ │ ├── another-file
│ │ ├── e/
│ │ │ ├── f/
│ │ │ ├── still-another-file-again
```
# Implementation
%%%
tag := "reader-io-implementation"
%%%
Internally, {lit}`doug` passes a configuration value downwards as it recursively traverses the directory structure.
This configuration contains two fields: {anchorName Config}`useASCII` determines whether to use Unicode box-drawing characters or ASCII vertical line and dash characters to indicate structure, and {anchorName Config}`currentPrefix` contains a string to prepend to each line of output.
As the current directory deepens, the prefix string accumulates indicators of being in a directory.
The configuration is a structure:
```anchor Config
structure Config where
useASCII : Bool := false
currentPrefix : String := ""
```
This structure has default definitions for both fields.
The default {anchorName Config}`Config` uses Unicode display with no prefix.
:::paragraph
Users who invoke {lit}`doug` will need to be able to provide command-line arguments.
The usage information is as follows:
```anchor usage
def usage : String :=
"Usage: doug [--ascii]
Options:
\t--ascii\tUse ASCII characters to display the directory structure"
```
Accordingly, a configuration can be constructed by examining a list of command-line arguments:
```anchor configFromArgs
def configFromArgs : List String → Option Config
| [] => some {} -- both fields default
| ["--ascii"] => some {useASCII := true}
| _ => none
```
:::
The {anchorName OldMain}`main` function is a wrapper around an inner worker, called {anchorName OldMain}`dirTree`, that shows the contents of a directory using a configuration.
Before calling {anchorName OldMain}`dirTree`, {anchorName OldMain}`main` is responsible for processing command-line arguments.
It must also return the appropriate exit code to the operating system:
```anchor OldMain
def main (args : List String) : IO UInt32 := do
match configFromArgs args with
| some config =>
dirTree config (← IO.currentDir)
pure 0
| none =>
IO.eprintln s!"Didn't understand argument(s) {" ".separate args}\n"
IO.eprintln usage
pure 1
```
{anchorName OldMain}`IO.eprintln` is a version of {anchorName OldShowFile}`IO.println` that outputs to standard error.
Not all paths should be shown in the directory tree.
In particular, files named {lit}`.` or {lit}`..` should be skipped, as they are actually features used for navigation rather than files _per se_.
Of those files that should be shown, there are two kinds: ordinary files and directories:
```anchor Entry
inductive Entry where
| file : String → Entry
| dir : String → Entry
```
To determine whether a file should be shown, along with which kind of entry it is, {lit}`doug` uses {anchorName toEntry}`toEntry`:
```anchor toEntry
def toEntry (path : System.FilePath) : IO (Option Entry) := do
match path.components.getLast? with
| none => pure (some (.dir ""))
| some "." | some ".." => pure none
| some name =>
pure (some (if (← path.isDir) then .dir name else .file name))
```
{anchorName names}`System.FilePath.components` converts a path into a list of path components, splitting the name at directory separators.
If there is no last component, then the path is the root directory.
If the last component is a special navigation file ({lit}`.` or {lit}`..`), then the file should be excluded.
Otherwise, directories and files are wrapped in the corresponding constructors.
Lean's logic has no way to know that directory trees are finite.
Indeed, some systems allow the construction of circular directory structures.
Thus, {anchorName OldDirTree}`dirTree` is declared {kw}`partial`:
```anchor OldDirTree
partial def dirTree (cfg : Config) (path : System.FilePath) : IO Unit := do
match ← toEntry path with
| none => pure ()
| some (.file name) => showFileName cfg name
| some (.dir name) =>
showDirName cfg name
let contents ← path.readDir
let newConfig := cfg.inDirectory
doList (contents.qsort dirLT).toList fun d =>
dirTree newConfig d.path
```
The call to {anchorName OldDirTree}`toEntry` is a {ref "nested-actions"}[nested action]—the parentheses are optional in positions where the arrow couldn't have any other meaning, such as {kw}`match`.
When the filename doesn't correspond to an entry in the tree (e.g. because it is {lit}`..`), {anchorName OldDirTree}`dirTree` does nothing.
When the filename points to an ordinary file, {anchorName OldDirTree}`dirTree` calls a helper to show it with the current configuration.
When the filename points to a directory, it is shown with a helper, and then its contents are recursively shown in a new configuration in which the prefix has been extended to account for being in a new directory.
The contents of the directory are sorted in order to make the output deterministic, compared according to {anchorName compareEntries'}`dirLT`.
```anchor compareEntries'
def dirLT (e1 : IO.FS.DirEntry) (e2 : IO.FS.DirEntry) : Bool :=
e1.fileName < e2.fileName
```
Showing the names of files and directories is achieved with {anchorName OldShowFile}`showFileName` and {anchorName OldShowFile}`showDirName`:
```anchor OldShowFile
def showFileName (cfg : Config) (file : String) : IO Unit := do
IO.println (cfg.fileName file)
def showDirName (cfg : Config) (dir : String) : IO Unit := do
IO.println (cfg.dirName dir)
```
Both of these helpers delegate to functions on {anchorName filenames}`Config` that take the ASCII vs Unicode setting into account:
```anchor filenames
def Config.preFile (cfg : Config) :=
if cfg.useASCII then "|--" else "├──"
def Config.preDir (cfg : Config) :=
if cfg.useASCII then "| " else "│ "
def Config.fileName (cfg : Config) (file : String) : String :=
s!"{cfg.currentPrefix}{cfg.preFile} {file}"
def Config.dirName (cfg : Config) (dir : String) : String :=
s!"{cfg.currentPrefix}{cfg.preFile} {dir}/"
```
Similarly, {anchorName inDirectory}`Config.inDirectory` extends the prefix with a directory marker:
```anchor inDirectory
def Config.inDirectory (cfg : Config) : Config :=
{cfg with currentPrefix := cfg.preDir ++ " " ++ cfg.currentPrefix}
```
Iterating an IO action over a list of directory contents is achieved using {anchorName doList}`doList`.
Because {anchorName doList}`doList` carries out all the actions in a list and does not base control-flow decisions on the values returned by any of the actions, the full power of {anchorName ConfigIO}`Monad` is not necessary, and it will work for any {anchorName doList}`Applicative`:
```anchor doList
def doList [Applicative f] : List α → (α → f Unit) → f Unit
| [], _ => pure ()
| x :: xs, action =>
action x *>
doList xs action
```
# Using a Custom Monad
%%%
tag := "reader-io-custom-monad"
%%%
While this implementation of {lit}`doug` works, manually passing the configuration around is verbose and error-prone.
The type system will not catch it if the wrong configuration is passed downwards, for instance.
A reader effect ensures that the same configuration is passed to all recursive calls, unless it is manually overridden, and it helps make the code less verbose.
To create a version of {anchorName ConfigIO}`IO` that is also a reader of {anchorName ConfigIO}`Config`, first define the type and its {anchorName ConfigIO}`Monad` instance, following the recipe from {ref "custom-environments"}[the evaluator example]:
```anchor ConfigIO
def ConfigIO (α : Type) : Type :=
Config → IO α
instance : Monad ConfigIO where
pure x := fun _ => pure x
bind result next := fun cfg => do
let v ← result cfg
next v cfg
```
The difference between this {anchorName ConfigIO}`Monad` instance and the one for {anchorName Reader (module := Examples.Monads.Class)}`Reader` is that this one uses {kw}`do`-notation in the {anchorName ConfigIO}`IO` monad as the body of the function that {anchorName ConfigIO}`bind` returns, rather than applying {anchorName ConfigIO}`next` directly to the value returned from {anchorName ConfigIO}`result`.
Any {anchorName ConfigIO}`IO` effects performed by {anchorName ConfigIO}`result` must occur before {anchorName ConfigIO}`next` is invoked, which is ensured by the {anchorName ConfigIO}`IO` monad's {anchorName ConfigIO}`bind` operator.
{anchorName ConfigIO}`ConfigIO` is not universe polymorphic because the underlying {anchorName ConfigIO}`IO` type is also not universe polymorphic.
Running a {anchorName ConfigIO}`ConfigIO` action involves transforming it into an {anchorName ConfigIO}`IO` action by providing it with a configuration:
```anchor ConfigIORun
def ConfigIO.run (action : ConfigIO α) (cfg : Config) : IO α :=
action cfg
```
This function is not really necessary, as a caller could simply provide the configuration directly.
However, naming the operation can make it easier to see which parts of the code are intended to run in which monad.
The next step is to define a means of accessing the current configuration as part of {anchorName ConfigIO}`ConfigIO`:
```anchor currentConfig
def currentConfig : ConfigIO Config :=
fun cfg => pure cfg
```
This is just like {anchorName Reader (module := Examples.Monads.Class)}`read` from {ref "custom-environments"}[the evaluator example], except it uses {anchorName ConfigIO}`IO`'s {anchorName ConfigIO}`pure` to return its value rather than doing so directly.
Because entering a directory modifies the current configuration for the scope of a recursive call, it will be necessary to have a way to override a configuration:
```anchor locally
def locally (change : Config → Config) (action : ConfigIO α) : ConfigIO α :=
fun cfg => action (change cfg)
```
Much of the code used in {lit}`doug` has no need for configurations, and {lit}`doug` calls ordinary Lean {anchorName ConfigIO}`IO` actions from the standard library that certainly don't need a {anchorName ConfigIO}`Config`.
Ordinary {anchorName ConfigIO}`IO` actions can be run using {anchorName runIO}`runIO`, which ignores the configuration argument:
```anchor runIO
def runIO (action : IO α) : ConfigIO α :=
fun _ => action
```
With these components, {anchorName MedShowFileDir}`showFileName` and {anchorName MedShowFileDir}`showDirName` can be updated to take their configuration arguments implicitly through the {anchorName ConfigIO}`ConfigIO` monad.
They use {ref "nested-actions"}[nested actions] to retrieve the configuration, and {anchorName runIO}`runIO` to actually execute the call to {anchorName MedShowFileDir}`IO.println`:
```anchor MedShowFileDir
def showFileName (file : String) : ConfigIO Unit := do
runIO (IO.println ((← currentConfig).fileName file))
def showDirName (dir : String) : ConfigIO Unit := do
runIO (IO.println ((← currentConfig).dirName dir))
```
In the new version of {anchorName MedDirTree}`dirTree`, the calls to {anchorName MedDirTree}`toEntry` and {anchorName MedDirTree}`readDir` are wrapped in {anchorName runIO}`runIO`.
Additionally, instead of building a new configuration and then requiring the programmer to keep track of which one to pass to recursive calls, it uses {anchorName MedDirTree}`locally` to naturally delimit the modified configuration to only a small region of the program, in which it is the _only_ valid configuration:
```anchor MedDirTree
partial def dirTree (path : System.FilePath) : ConfigIO Unit := do
match ← runIO (toEntry path) with
| none => pure ()
| some (.file name) => showFileName name
| some (.dir name) =>
showDirName name
let contents ← runIO path.readDir
locally (·.inDirectory)
(doList (contents.qsort dirLT).toList fun d =>
dirTree d.path)
```
The new version of {anchorName MedMain}`main` uses {anchorName ConfigIORun}`ConfigIO.run` to invoke {anchorName MedMain}`dirTree` with the initial configuration:
```anchor MedMain
def main (args : List String) : IO UInt32 := do
match configFromArgs args with
| some config =>
(dirTree (← IO.currentDir)).run config
pure 0
| none =>
IO.eprintln s!"Didn't understand argument(s) {" ".separate args}\n"
IO.eprintln usage
pure 1
```
This custom monad has a number of advantages over passing configurations manually:
1. It is easier to ensure that configurations are passed down unchanged, except when changes are desired
2. The concern of passing the configuration onwards is more clearly separated from the concern of printing directory contents
3. As the program grows, there will be more and more intermediate layers that do nothing with configurations except propagate them, and these layers don't need to be rewritten as the configuration logic changes
However, there are also some clear downsides:
1. As the program evolves and the monad requires more features, each of the basic operators such as {anchorName locally}`locally` and {anchorName currentConfig}`currentConfig` will need to be updated
2. Wrapping ordinary {anchorName ConfigIO}`IO` actions in {anchorName runIO}`runIO` is noisy and distracts from the flow of the program
3. Writing monads instances by hand is repetitive, and the technique for adding a reader effect to another monad is a design pattern that requires documentation and communication overhead
Using a technique called _monad transformers_, all of these downsides can be addressed.
A monad transformer takes a monad as an argument and returns a new monad.
Monad transformers consist of:
1. A definition of the transformer itself, which is typically a function from types to types
2. A {anchorName ConfigIO}`Monad` instance that assumes the inner type is already a monad
3. An operator to “lift” an action from the inner monad to the transformed monad, akin to {anchorName runIO}`runIO`
# Adding a Reader to Any Monad
%%%
tag := "ReaderT"
%%%
Adding a reader effect to {anchorName ConfigIO}`IO` was accomplished in {anchorName ConfigIO}`ConfigIO` by wrapping {anchorTerm ConfigIO}`IO α` in a function type.
The Lean standard library contains a function that can do this to _any_ polymorphic type, called {anchorName MyReaderT}`ReaderT`:
```anchor MyReaderT
def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) :
Type (max u v) :=
ρ → m α
```
Its arguments are as follows:
* {anchorName MyReaderT}`ρ` is the environment that is accessible to the reader
* {anchorName MyReaderT}`m` is the monad that is being transformed, such as {anchorName ConfigIO}`IO`
* {anchorName MyReaderT}`α` is the type of values being returned by the monadic computation
Both {anchorName MyReaderT}`α` and {anchorName MyReaderT}`ρ` are in the same universe because the operator that retrieves the environment in the monad will have type {anchorTerm MyReaderTread}`m ρ`.
:::paragraph
With {anchorName MyReaderT}`ReaderT`, {anchorName ConfigIO}`ConfigIO` becomes:
```anchor ReaderTConfigIO
abbrev ConfigIO (α : Type) : Type := ReaderT Config IO α
```
It is an {kw}`abbrev` because {anchorName ReaderTConfigIO}`ReaderT` has many useful features defined in the standard library that a non-reducible definition would hide.
Rather than taking responsibility for making these work directly for {anchorName ConfigIO}`ConfigIO`, it's easier to simply have {anchorName ReaderTConfigIO}`ConfigIO` behave identically to {anchorTerm ReaderTConfigIO}`ReaderT Config IO`.
:::
:::paragraph
The manually-written {anchorName currentConfig}`currentConfig` obtained the environment out of the reader.
This effect can be defined in a generic form for all uses of {anchorName MyReaderTread}`ReaderT`, under the name {anchorName MonadReader}`read`:
```anchor MyReaderTread
def read [Monad m] : ReaderT ρ m ρ :=
fun env => pure env
```
However, not every monad that provides a reader effect is built with {anchorName MyReaderT}`ReaderT`.
The type class {anchorName MonadReader}`MonadReader` allows any monad to provide a {anchorName MonadReader}`read` operator:
```anchor MonadReader
class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) :
Type (max (u + 1) v) where
read : m ρ
instance [Monad m] : MonadReader ρ (ReaderT ρ m) where
read := fun env => pure env
export MonadReader (read)
```
The type {anchorName MonadReader}`ρ` is an output parameter because any given monad typically only provides a single type of environment through a reader, so automatically selecting it when the monad is known makes programs more convenient to write.
:::
The {anchorName ConfigIO}`Monad` instance for {anchorName MyReaderT}`ReaderT` is essentially the same as the {anchorName ConfigIO}`Monad` instance for {anchorName ConfigIO}`ConfigIO`, except {anchorName ConfigIO}`IO` has been replaced by some arbitrary monad argument {anchorName MonadMyReaderT}`m`:
```anchor MonadMyReaderT
instance [Monad m] : Monad (ReaderT ρ m) where
pure x := fun _ => pure x
bind result next := fun env => do
let v ← result env
next v env
```
The next step is to eliminate uses of {anchorName runIO}`runIO`.
When Lean encounters a mismatch in monad types, it automatically attempts to use a type class called {anchorName MyMonadLift}`MonadLift` to transform the actual monad into the expected monad.
This process is similar to the use of coercions.
{anchorName MyMonadLift}`MonadLift` is defined as follows:
```anchor MyMonadLift
class MonadLift (m : Type u → Type v) (n : Type u → Type w) where
monadLift : {α : Type u} → m α → n α
```
The method {anchorName MyMonadLift}`monadLift` translates from the monad {anchorName MyMonadLift}`m` to the monad {anchorName MyMonadLift}`n`.
The process is called “lifting” because it takes an action in the embedded monad and makes it into an action in the surrounding monad.
In this case, it will be used to “lift” from {anchorName ConfigIO}`IO` to {anchorTerm ReaderTConfigIO}`ReaderT Config IO`, though the instance works for _any_ inner monad {anchorName MonadLiftReaderT}`m`:
```anchor MonadLiftReaderT
instance : MonadLift m (ReaderT ρ m) where
monadLift action := fun _ => action
```
The implementation of {anchorName MonadLiftReaderT}`monadLift` is very similar to that of {anchorName runIO}`runIO`.
Indeed, it is enough to define {anchorName showFileAndDir}`showFileName` and {anchorName showFileAndDir}`showDirName` without using {anchorName runIO}`runIO`:
```anchor showFileAndDir
def showFileName (file : String) : ConfigIO Unit := do
IO.println s!"{(← read).currentPrefix} {file}"
def showDirName (dir : String) : ConfigIO Unit := do
IO.println s!"{(← read).currentPrefix} {dir}/"
```
One final operation from the original {anchorName ConfigIO}`ConfigIO` remains to be translated to a use of {anchorName MyReaderT}`ReaderT`: {anchorName locally}`locally`.
The definition can be translated directly to {anchorName MyReaderT}`ReaderT`, but the Lean standard library provides a more general version.
The standard version is called {anchorName MyMonadWithReader}`withReader`, and it is part of a type class called {anchorName MyMonadWithReader}`MonadWithReader`:
```anchor MyMonadWithReader
class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where
withReader {α : Type u} : (ρ → ρ) → m α → m α
```
Just as in {anchorName MonadReader}`MonadReader`, the environment {anchorName MyMonadWithReader}`ρ` is an {anchorName MyMonadWithReader}`outParam`.
The {anchorName exportWithReader}`withReader` operation is exported, so that it doesn't need to be written with the type class name before it:
```anchor exportWithReader
export MonadWithReader (withReader)
```
The instance for {anchorName ReaderTWithReader}`ReaderT` is essentially the same as the definition of {anchorName locally}`locally`:
```anchor ReaderTWithReader
instance : MonadWithReader ρ (ReaderT ρ m) where
withReader change action :=
fun cfg => action (change cfg)
```
With these definitions in place, the new version of {anchorName readerTDirTree}`dirTree` can be written:
```anchor readerTDirTree
partial def dirTree (path : System.FilePath) : ConfigIO Unit := do
match ← toEntry path with
| none => pure ()
| some (.file name) => showFileName name
| some (.dir name) =>
showDirName name
let contents ← path.readDir
withReader (·.inDirectory)
(doList (contents.qsort dirLT).toList fun d =>
dirTree d.path)
```
Aside from replacing {anchorName locally}`locally` with {anchorName readerTDirTree}`withReader`, it is the same as before.
Replacing the custom {anchorName ConfigIO}`ConfigIO` type with {anchorName MonadMyReaderT}`ReaderT` did not save a large number of lines of code in this section.
However, rewriting the code using components from the standard library does have long-term benefits.
First, readers who know about {anchorName MyReaderT}`ReaderT` don't need to take time to understand the {anchorName ConfigIO}`Monad` instance for {anchorName ConfigIO}`ConfigIO`, working backwards to the meaning of monad itself.
Instead, they can be confident in their initial understanding.
Next, adding further effects to the monad (such as a state effect to count the files in each directory and display a count at the end) requires far fewer changes to the code, because the monad transformers and {anchorName MonadLiftReaderT}`MonadLift` instances provided in the library work well together.
Finally, using a set of type classes included in the standard library, polymorphic code can be written in such a way that it can work with a variety of monads without having to care about details like the order in which the monad transformers were applied.
Just as some functions work in any monad, others can work in any monad that provides a certain type of state, or a certain type of exceptions, without having to specifically describe the _way_ in which a particular concrete monad provides the state or exceptions.
# Exercises
%%%
tag := "reader-io-exercises"
%%%
## Controlling the Display of Dotfiles
%%%
tag := none
%%%
Files whose names begin with a dot character ({lit}`'.'`) typically represent files that should usually be hidden, such as source-control metadata and configuration files.
Modify {lit}`doug` with an option to show or hide filenames that begin with a dot.
This option should be controlled with a {lit}`-a` command-line option.
## Starting Directory as Argument
%%%
tag := none
%%%
Modify {lit}`doug` so that it takes a starting directory as an additional command-line argument. |
fp-lean/book/FPLean/MonadTransformers/Order.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.MonadTransformers.Defs"
#doc (Manual) "Ordering Monad Transformers" =>
%%%
tag := "monad-transformer-order"
%%%
When composing a monad from a stack of monad transformers, it's important to be aware that the order in which the monad transformers are layered matters.
Different orderings of the same set of transformers result in different monads.
This version of {anchorName countLettersClassy}`countLetters` is just like the previous version, except it uses type classes to describe the set of available effects instead of providing a concrete monad:
```anchor countLettersClassy
def countLetters [Monad m] [MonadState LetterCounts m] [MonadExcept Err m]
(str : String) : m Unit :=
let rec loop (chars : List Char) := do
match chars with
| [] => pure ()
| c :: cs =>
if c.isAlpha then
if vowels.contains c then
modify fun st => {st with vowels := st.vowels + 1}
else if consonants.contains c then
modify fun st => {st with consonants := st.consonants + 1}
else -- modified or non-English letter
pure ()
else throw (.notALetter c)
loop cs
loop str.toList
```
The state and exception monad transformers can be combined in two different orders, each resulting in a monad that has instances of both type classes:
```anchor SomeMonads
abbrev M1 := StateT LetterCounts (ExceptT Err Id)
abbrev M2 := ExceptT Err (StateT LetterCounts Id)
```
When run on input for which the program does not throw an exception, both monads yield similar results:
```anchor countLettersM1Ok
#eval countLetters (m := M1) "hello" ⟨0, 0⟩
```
```anchorInfo countLettersM1Ok
Except.ok ((), { vowels := 2, consonants := 3 })
```
```anchor countLettersM2Ok
#eval countLetters (m := M2) "hello" ⟨0, 0⟩
```
```anchorInfo countLettersM2Ok
(Except.ok (), { vowels := 2, consonants := 3 })
```
However, there is a subtle difference between these return values.
In the case of {anchorName M1eval}`M1`, the outermost constructor is {anchorName MonadExceptT}`Except.ok`, and it contains a pair of the unit constructor with the final state.
In the case of {anchorName M2eval}`M2`, the outermost constructor is the pair, which contains {anchorName MonadExceptT}`Except.ok` applied only to the unit constructor.
The final state is outside of {anchorName MonadExceptT}`Except.ok`.
In both cases, the program returns the counts of vowels and consonants.
On the other hand, only one monad yields a count of vowels and consonants when the string causes an exception to be thrown.
Using {anchorName M1eval}`M1`, only an exception value is returned:
```anchor countLettersM1Error
#eval countLetters (m := M1) "hello!" ⟨0, 0⟩
```
```anchorInfo countLettersM1Error
Except.error (StEx.Err.notALetter '!')
```
Using {anchorName SomeMonads}`M2`, the exception value is paired with the state as it was at the time that the exception was thrown:
```anchor countLettersM2Error
#eval countLetters (m := M2) "hello!" ⟨0, 0⟩
```
```anchorInfo countLettersM2Error
(Except.error (StEx.Err.notALetter '!'), { vowels := 2, consonants := 3 })
```
It might be tempting to think that {anchorName SomeMonads}`M2` is superior to {anchorName SomeMonads}`M1` because it provides more information that might be useful when debugging.
The same program might compute _different_ answers in {anchorName SomeMonads}`M1` than it does in {anchorName SomeMonads}`M2`, and there's no principled reason to say that one of these answers is necessarily better than the other.
This can be seen by adding a step to the program that handles exceptions:
```anchor countWithFallback
def countWithFallback
[Monad m] [MonadState LetterCounts m] [MonadExcept Err m]
(str : String) : m Unit :=
try
countLetters str
catch _ =>
countLetters "Fallback"
```
This program always succeeds, but it might succeed with different results.
If no exception is thrown, then the results are the same as {anchorName countWithFallback}`countLetters`:
```anchor countWithFallbackM1Ok
#eval countWithFallback (m := M1) "hello" ⟨0, 0⟩
```
```anchorInfo countWithFallbackM1Ok
Except.ok ((), { vowels := 2, consonants := 3 })
```
```anchor countWithFallbackM2Ok
#eval countWithFallback (m := M2) "hello" ⟨0, 0⟩
```
```anchorInfo countWithFallbackM2Ok
(Except.ok (), { vowels := 2, consonants := 3 })
```
However, if the exception is thrown and caught, then the final states are very different.
With {anchorName countWithFallbackM1Error}`M1`, the final state contains only the letter counts from {anchorTerm countWithFallback}`"Fallback"`:
```anchor countWithFallbackM1Error
#eval countWithFallback (m := M1) "hello!" ⟨0, 0⟩
```
```anchorInfo countWithFallbackM1Error
Except.ok ((), { vowels := 2, consonants := 6 })
```
With {anchorName countWithFallbackM2Error}`M2`, the final state contains letter counts from both {anchorTerm countWithFallbackM2Error}`"hello!"` and from {anchorTerm countWithFallback}`"Fallback"`, as one would expect in an imperative language:
```anchor countWithFallbackM2Error
#eval countWithFallback (m := M2) "hello!" ⟨0, 0⟩
```
```anchorInfo countWithFallbackM2Error
(Except.ok (), { vowels := 4, consonants := 9 })
```
In {anchorName countWithFallbackM1Error}`M1`, throwing an exception “rolls back” the state to where the exception was caught.
In {anchorName countLettersM2Error}`M2`, modifications to the state persist across the throwing and catching of exceptions.
This difference can be seen by unfolding the definitions of {anchorName SomeMonads}`M1` and {anchorName SomeMonads}`M2`.
{anchorTerm M1eval}`M1 α` unfolds to {anchorTerm M1eval}`LetterCounts → Except Err (α × LetterCounts)`, and {anchorTerm M2eval}`M2 α` unfolds to {anchorTerm M2eval}`LetterCounts → Except Err α × LetterCounts`.
That is to say, {anchorTerm M1eval}`M1 α` describes functions that take an initial letter count, returning either an error or an {anchorName M1eval}`α` paired with updated counts.
When an exception is thrown in {anchorName M1eval}`M1`, there is no final state.
{anchorTerm M2eval}`M2 α` describes functions that take an initial letter count and return a new letter count paired with either an error or an {anchorName M2eval}`α`.
When an exception is thrown in {anchorName M2eval}`M2`, it is accompanied by a state.
# Commuting Monads
%%%
tag := "commuting-monads"
%%%
In the jargon of functional programming, two monad transformers are said to _commute_ if they can be re-ordered without the meaning of the program changing.
The fact that the result of the program can differ when {anchorName SomeMonads}`StateT` and {anchorName SomeMonads}`ExceptT` are reordered means that state and exceptions do not commute.
In general, monad transformers should not be expected to commute.
Even though not all monad transformers commute, some do.
For example, two uses of {anchorName SomeMonads}`StateT` can be re-ordered.
Expanding the definitions in {anchorTerm StateTDoubleA}`StateT σ (StateT σ' Id) α` yields the type {anchorTerm StateTDoubleA}`σ → σ' → ((α × σ) × σ')`, and {anchorTerm StateTDoubleB}`StateT σ' (StateT σ Id) α` yields {anchorTerm StateTDoubleB}`σ' → σ → ((α × σ') × σ)`.
In other words, the differences between them are that they nest the {anchorName StateTDoubleA}`σ` and {anchorName StateTDoubleA}`σ'` types in different places in the return type, and they accept their arguments in a different order.
Any client code will still need to provide the same inputs, and it will still receive the same outputs.
Most programming languages that have both mutable state and exceptions work like {anchorName SomeMonads}`M2`.
In those languages, state that _should_ be rolled back when an exception is thrown is difficult to express, and it usually needs to be simulated in a manner that looks much like the passing of explicit state values in {anchorName SomeMonads}`M1`.
Monad transformers grant the freedom to choose an interpretation of effect ordering that works for the problem at hand, with both choices being equally easy to program with.
However, they also require care to be taken in the choice of ordering of transformers.
With great expressive power comes the responsibility to check that what's being expressed is what is intended, and the type signature of {anchorName countWithFallback}`countWithFallback` is probably more polymorphic than it should be.
# Exercises
%%%
tag := "monad-transformer-order-exercises"
%%%
* Check that {anchorName m}`ReaderT` and {anchorName SomeMonads}`StateT` commute by expanding their definitions and reasoning about the resulting types.
* Do {anchorName m}`ReaderT` and {anchorName SomeMonads}`ExceptT` commute? Check your answer by expanding their definitions and reasoning about the resulting types.
* Construct a monad transformer {lit}`ManyT` based on the definition of {anchorName Many (module:=Examples.Monads.Many)}`Many`, with a suitable {anchorName AlternativeOptionT}`Alternative` instance. Check that it satisfies the {anchorName AlternativeOptionT}`Monad` contract.
* Does {lit}`ManyT` commute with {anchorName SomeMonads}`StateT`? If so, check your answer by expanding definitions and reasoning about the resulting types. If not, write a program in {lit}`ManyT (StateT σ Id)` and a program in {lit}`StateT σ (ManyT Id)`. Each program should be one that makes more sense for the given ordering of monad transformers. |
fp-lean/book/FPLean/MonadTransformers/Conveniences.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.MonadTransformers.Conveniences"
#doc (Manual) "Additional Conveniences" =>
%%%
tag := "monad-transformer-conveniences"
%%%
# Pipe Operators
%%%
tag := "pipe-operators"
%%%
Functions are normally written before their arguments.
When reading a program from left to right, this promotes a view in which the function's _output_ is paramount—the function has a goal to achieve (that is, a value to compute), and it receives arguments to support it in this process.
But some programs are easier to understand in terms of an input that is successively refined to produce the output.
For these situations, Lean provides a _pipeline_ operator which is similar to the that provided by F#.
Pipeline operators are useful in the same situations as Clojure's threading macros.
The pipeline {anchorTerm pipelineShort}`E₁ |> E₂` is short for {anchorTerm pipelineShort}`E₂ E₁`.
For example, evaluating:
```anchor some5
#eval some 5 |> toString
```
results in:
```anchorInfo some5
"(some 5)"
```
While this change of emphasis can make some programs more convenient to read, pipelines really come into their own when they contain many components.
With the definition:
```anchor times3
def times3 (n : Nat) : Nat := n * 3
```
the following pipeline:
```anchor itIsFive
#eval 5 |> times3 |> toString |> ("It is " ++ ·)
```
yields:
```anchorInfo itIsFive
"It is 15"
```
More generally, a series of pipelines {anchorTerm pipeline}`E₁ |> E₂ |> E₃ |> E₄` is short for nested function applications {anchorTerm pipeline}`E₄ (E₃ (E₂ E₁))`.
Pipelines may also be written in reverse.
In this case, they do not place the subject of data transformation first; however, in cases where many nested parentheses pose a challenge for readers, they can clarify the steps of application.
The prior example could be equivalently written as:
```anchor itIsAlsoFive
#eval ("It is " ++ ·) <| toString <| times3 <| 5
```
which is short for:
```anchor itIsAlsoFiveParens
#eval ("It is " ++ ·) (toString (times3 5))
```
Lean's method dot notation that uses the name of the type before the dot to resolve the namespace of the operator after the dot serves a similar purpose to pipelines.
Even without the pipeline operator, it is possible to write {anchorTerm listReverse}`[1, 2, 3].reverse` instead of {anchorTerm listReverse}`List.reverse [1, 2, 3]`.
However, the pipeline operator is also useful for dotted functions when using many of them.
{anchorTerm listReverseDropReverse}`([1, 2, 3].reverse.drop 1).reverse` can also be written as {anchorTerm listReverseDropReverse}`[1, 2, 3] |> List.reverse |> List.drop 1 |> List.reverse`.
This version avoids having to parenthesize expressions simply because they accept arguments, and it recovers the convenience of a chain of method calls in languages like Kotlin or C#.
However, it still requires the namespace to be provided by hand.
As a final convenience, Lean provides the “pipeline dot” operator, which groups functions like the pipeline but uses the name of the type to resolve namespaces.
With “pipeline dot”, the example can be rewritten to {anchorTerm listReverseDropReversePipe}`[1, 2, 3] |>.reverse |>.drop 1 |>.reverse`.
# Infinite Loops
%%%
tag := "infinite-loops"
%%%
Within a {kw}`do`-block, the {kw}`repeat` keyword introduces an infinite loop.
For example, a program that spams the string {anchorTerm spam}`"Spam!"` can use it:
```anchor spam
def spam : IO Unit := do
repeat IO.println "Spam!"
```
A {kw}`repeat` loop supports {kw}`break` and {kw}`continue`, just like {kw}`for` loops.
The {anchorName dump (module := FelineLib)}`dump` function from the {ref "streams"}[implementation of {lit}`feline`] uses a recursive function to run forever:
```anchor dump (module := FelineLib)
partial def dump (stream : IO.FS.Stream) : IO Unit := do
let buf ← stream.read bufsize
if buf.isEmpty then
pure ()
else
let stdout ← IO.getStdout
stdout.write buf
dump stream
```
This function can be greatly shortened using {kw}`repeat`:
```anchor dump
def dump (stream : IO.FS.Stream) : IO Unit := do
let stdout ← IO.getStdout
repeat do
let buf ← stream.read bufsize
if buf.isEmpty then break
stdout.write buf
```
Neither {anchorName spam}`spam` nor {anchorName dump}`dump` need to be declared as {kw}`partial` because they are not themselves infinitely recursive.
Instead, {kw}`repeat` makes use of a type whose {anchorTerm names}`ForM` instance is {kw}`partial`.
Partiality does not “infect” calling functions.
# While Loops
%%%
tag := "while-loops"
%%%
When programming with local mutability, {kw}`while` loops can be a convenient alternative to {kw}`repeat` with an {kw}`if`-guarded {kw}`break`:
```anchor dumpWhile
def dump (stream : IO.FS.Stream) : IO Unit := do
let stdout ← IO.getStdout
let mut buf ← stream.read bufsize
while not buf.isEmpty do
stdout.write buf
buf ← stream.read bufsize
```
Behind the scenes, {kw}`while` is just a simpler notation for {kw}`repeat`. |
fp-lean/book/FPLean/MonadTransformers/Summary.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.MonadTransformers"
#doc (Manual) "Summary" =>
%%%
tag := "monad-transformer-summary"
%%%
# Combining Monads
%%%
tag := none
%%%
When writing a monad from scratch, there are design patterns that tend to describe the ways that each effect is added to the monad.
Reader effects are added by having the monad's type be a function from the reader's environment, state effects are added by including a function from the initial state to the value paired with the final state, failure or exceptions are added by including a sum type in the return type, and logging or other output is added by including a product type in the return type.
Existing monads can be made part of the return type as well, allowing their effects to be included in the new monad.
These design patterns are made into a library of reusable software components by defining _monad transformers_, which add an effect to some base monad.
Monad transformers take the simpler monad types as arguments, returning the enhanced monad types.
At a minimum, a monad transformer should provide the following instances:
1. A {anchorName Summary}`Monad` instance that assumes the inner type is already a monad
2. A {anchorName Summary}`MonadLift` instance to translate an action from the inner monad to the transformed monad
Monad transformers may be implemented as polymorphic structures or inductive datatypes, but they are most often implemented as functions from the underlying monad type to the enhanced monad type.
# Type Classes for Effects
%%%
tag := none
%%%
A common design pattern is to implement a particular effect by defining a monad that has the effect, a monad transformer that adds it to another monad, and a type class that provides a generic interface to the effect.
This allows programs to be written that merely specify which effects they need, so the caller can provide any monad that has the right effects.
Sometimes, auxiliary type information (e.g. the state's type in a monad that provides state, or the exception's type in a monad that provides exceptions) is an output parameter, and sometimes it is not.
The output parameter is most useful for simple programs that use each kind of effect only once, but it risks having the type checker commit to a the wrong type too early when multiple instances of the same effect are used in a given program.
Thus, both versions are typically provided, with the ordinary-parameter version of the type class having a name that ends in {lit}`-Of`.
# Monad Transformers Don't Commute
%%%
tag := none
%%%
It is important to note that changing the order of transformers in a monad can change the meaning of programs that use the monad.
For instance, re-ordering {anchorName Summary}`StateT` and {anchorTerm Summary}`ExceptT` can result either in programs that lose state modifications when exceptions are thrown or programs that keep changes.
While most imperative languages provide only the latter, the increased flexibility provided by monad transformers demands thought and attention to choose the correct variety for the task at hand.
# {kw}`do`-Notation for Monad Transformers
%%%
tag := none
%%%
Lean's {kw}`do`-blocks support early return, in which the block is terminated with some value, locally mutable variables, {kw}`for`-loops with {kw}`break` and {kw}`continue`, and single-branched {kw}`if`-statements.
While this may seem to be introducing imperative features that would get in the way of using Lean to write proofs, it is in fact nothing more than a more convenient syntax for certain common uses of monad transformers.
Behind the scenes, whatever monad the {kw}`do`-block is written in is transformed by appropriate uses of {anchorName Summary}`ExceptT` and {anchorName Summary}`StateT` to support these additional effects. |
fp-lean/book/FPLean/MonadTransformers/Do.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.MonadTransformers.Do"
#doc (Manual) "More do Features" =>
%%%
tag := "more-do-features"
%%%
Lean's {kw}`do`-notation provides a syntax for writing programs with monads that resembles imperative programming languages.
In addition to providing a convenient syntax for programs with monads, {kw}`do`-notation provides syntax for using certain monad transformers.
# Single-Branched {kw}`if`
%%%
tag := "single-branched-if"
%%%
When working in a monad, a common pattern is to carry out a side effect only if some condition is true.
For instance, {anchorName countLettersModify (module := Examples.MonadTransformers.Defs)}`countLetters` contains a check for vowels or consonants, and letters that are neither have no effect on the state.
This is captured by having the {kw}`else` branch evaluate to {anchorTerm countLettersModify (module := Examples.MonadTransformers.Defs)}`pure ()`, which has no effects:
```anchor countLettersModify (module := Examples.MonadTransformers.Defs)
def countLetters (str : String) : StateT LetterCounts (Except Err) Unit :=
let rec loop (chars : List Char) := do
match chars with
| [] => pure ()
| c :: cs =>
if c.isAlpha then
if vowels.contains c then
modify fun st => {st with vowels := st.vowels + 1}
else if consonants.contains c then
modify fun st => {st with consonants := st.consonants + 1}
else -- modified or non-English letter
pure ()
else throw (.notALetter c)
loop cs
loop str.toList
```
When an {kw}`if` is a statement in a {kw}`do`-block, rather than being an expression, then {anchorTerm countLettersModify (module:=Examples.MonadTransformers.Defs)}`else pure ()` can simply be omitted, and Lean inserts it automatically.
The following definition of {anchorName countLettersNoElse}`countLetters` is completely equivalent:
```anchor countLettersNoElse
def countLetters (str : String) : StateT LetterCounts (Except Err) Unit :=
let rec loop (chars : List Char) := do
match chars with
| [] => pure ()
| c :: cs =>
if c.isAlpha then
if vowels.contains c then
modify fun st => {st with vowels := st.vowels + 1}
else if consonants.contains c then
modify fun st => {st with consonants := st.consonants + 1}
else throw (.notALetter c)
loop cs
loop str.toList
```
A program that uses a state monad to count the entries in a list that satisfy some monadic check can be written as follows:
```anchor count
def count [Monad m] [MonadState Nat m] (p : α → m Bool) : List α → m Unit
| [] => pure ()
| x :: xs => do
if ← p x then
modify (· + 1)
count p xs
```
Similarly, {lit}`if not E1 then STMT...` can instead be written {lit}`unless E1 do STMT...`.
The converse of {anchorName count}`count` that counts entries that don't satisfy the monadic check can be written by replacing {kw}`if` with {kw}`unless`:
```anchor countNot
def countNot [Monad m] [MonadState Nat m] (p : α → m Bool) : List α → m Unit
| [] => pure ()
| x :: xs => do
unless ← p x do
modify (· + 1)
countNot p xs
```
Understanding single-branched {kw}`if` and {kw}`unless` does not require thinking about monad transformers.
They simply replace the missing branch with {anchorTerm count}`pure ()`.
The remaining extensions in this section, however, require Lean to automatically rewrite the {kw}`do`-block to add a local transformer on top of the monad that the {kw}`do`-block is written in.
# Early Return
%%%
tag := "early-return"
%%%
The standard library contains a function {anchorName findHuh}`List.find?` that returns the first entry in a list that satisfies some check.
A simple implementation that doesn't make use of the fact that {anchorName findHuh}`Option` is a monad loops over the list using a recursive function, with an {kw}`if` to stop the loop when the desired entry is found:
```anchor findHuhSimple
def List.find? (p : α → Bool) : List α → Option α
| [] => none
| x :: xs =>
if p x then
some x
else
find? p xs
```
Imperative languages typically sport the {kw}`return` keyword that aborts the execution of a function, immediately returning some value to the caller.
In Lean, this is available in {kw}`do`-notation, and {kw}`return` halts the execution of a {kw}`do`-block, with {kw}`return`'s argument being the value returned from the monad.
In other words, {anchorName findHuhFancy}`List.find?` could have been written like this:
```anchor findHuhFancy
def List.find? (p : α → Bool) : List α → Option α
| [] => failure
| x :: xs => do
if p x then return x
find? p xs
```
Early return in imperative languages is a bit like an exception that can only cause the current stack frame to be unwound.
Both early return and exceptions terminate execution of a block of code, effectively replacing the surrounding code with the thrown value.
Behind the scenes, early return in Lean is implemented using a version of {anchorName runCatch}`ExceptT`.
Each {kw}`do`-block that uses early return is wrapped in an exception handler (in the sense of the function {anchorName MonadExcept (module:=Examples.MonadTransformers.Defs)}`tryCatch`).
Early returns are translated to throwing the value as an exception, and the handlers catch the thrown value and return it immediately.
In other words, the {kw}`do`-block's original return value type is also used as the exception type.
Making this more concrete, the helper function {anchorName runCatch}`runCatch` strips a layer of {anchorName runCatch}`ExceptT` from the top of a monad transformer stack when the exception type and return type are the same:
```anchor runCatch
def runCatch [Monad m] (action : ExceptT α m α) : m α := do
match ← action with
| Except.ok x => pure x
| Except.error x => pure x
```
The {kw}`do`-block in {anchorName findHuh}`List.find?` that uses early return is translated to a {kw}`do`-block that does not use early return by wrapping it in a use of {anchorName desugaredFindHuh}`runCatch`, and replacing early returns with {anchorName desugaredFindHuh}`throw`:
```anchor desugaredFindHuh
def List.find? (p : α → Bool) : List α → Option α
| [] => failure
| x :: xs =>
runCatch do
if p x then throw x else pure ()
monadLift (find? p xs)
```
Another situation in which early return is useful is command-line applications that terminate early if the arguments or input are incorrect.
Many programs begin with a section that validates arguments and inputs before proceeding to the main body of the program.
The following version of {ref "running-a-program"}[the greeting program {lit}`hello-name`] checks that no command-line arguments were provided:
```anchor main (module := EarlyReturn)
def main (argv : List String) : IO UInt32 := do
let stdin ← IO.getStdin
let stdout ← IO.getStdout
let stderr ← IO.getStderr
unless argv == [] do
stderr.putStrLn s!"Expected no arguments, but got {argv.length}"
return 1
stdout.putStrLn "How would you like to be addressed?"
stdout.flush
let name := (← stdin.getLine).trim
if name == "" then
stderr.putStrLn s!"No name provided"
return 1
stdout.putStrLn s!"Hello, {name}!"
return 0
```
Running it with no arguments and typing the name {lit}`David` yields the same result as the previous version:
```commands «early-return» "early-return"
$ expect -f ./run # lean --run EarlyReturn.lean
How would you like to be addressed?
David
Hello, David!
```
Providing the name as a command-line argument instead of an answer causes an error:
```commands «early-return» "early-return"
$ expect -f ./too-many-args # lean --run EarlyReturn.lean David
Expected no arguments, but got 1
```
And providing no name causes the other error:
```commands «early-return» "early-return"
$ expect -f ./no-name # lean --run EarlyReturn.lean
How would you like to be addressed?
No name provided
```
The program that uses early return avoids needing to nest the control flow, as is done in this version that does not use early return:
```anchor nestedmain (module := EarlyReturn)
def main (argv : List String) : IO UInt32 := do
let stdin ← IO.getStdin
let stdout ← IO.getStdout
let stderr ← IO.getStderr
if argv != [] then
stderr.putStrLn s!"Expected no arguments, but got {argv.length}"
pure 1
else
stdout.putStrLn "How would you like to be addressed?"
stdout.flush
let name := (← stdin.getLine).trim
if name == "" then
stderr.putStrLn s!"No name provided"
pure 1
else
stdout.putStrLn s!"Hello, {name}!"
pure 0
```
One important difference between early return in Lean and early return in imperative languages is that Lean's early return applies only to the current {kw}`do`-block.
When the entire definition of a function is in the same {kw}`do` block, this difference doesn't matter.
But if {kw}`do` occurs underneath some other structures, then the difference becomes apparent.
For example, given the following definition of {anchorName greet}`greet`:
```anchor greet
def greet (name : String) : String :=
"Hello, " ++ Id.run do return name
```
the expression {anchorTerm greetDavid}`greet "David"` evaluates to {anchorTerm greetDavid}`"Hello, David"`, not just {anchorTerm greetDavid}`"David"`.
# Loops
%%%
tag := "loops"
%%%
Just as every program with mutable state can be rewritten to a program that passes the state as arguments, every loop can be rewritten as a recursive function.
From one perspective, {anchorName findHuh}`List.find?` is most clear as a recursive function.
After all, its definition mirrors the structure of the list: if the head passes the check, then it should be returned; otherwise look in the tail.
When no more entries remain, the answer is {anchorName findHuhSimple}`none`.
From another perspective, {anchorName findHuh}`List.find?` is most clear as a loop.
After all, the program consults the entries in order until a satisfactory one is found, at which point it terminates.
If the loop terminates without having returned, the answer is {anchorName findHuhSimple}`none`.
## Looping with ForM
%%%
tag := "looping-with-forM"
%%%
Lean includes a type class that describes looping over a container type in some monad.
This class is called {anchorName ForM}`ForM`:
```anchor ForM
class ForM (m : Type u → Type v) (γ : Type w₁)
(α : outParam (Type w₂)) where
forM [Monad m] : γ → (α → m PUnit) → m PUnit
```
This class is quite general.
The parameter {anchorName ForM}`m` is a monad with some desired effects, {anchorName ForM}`γ` is the collection to be looped over, and {anchorName ForM}`α` is the type of elements from the collection.
Typically, {anchorName ForM}`m` is allowed to be any monad, but it is possible to have a data structure that e.g. only supports looping in {anchorName printArray}`IO`.
The method {anchorName ForM}`forM` takes a collection, a monadic action to be run for its effects on each element from the collection, and is then responsible for running the actions.
The instance for {anchorName ListForM}`List` allows {anchorName ListForM}`m` to be any monad, it sets {anchorName ForM}`γ` to be {anchorTerm ListForM}`List α`, and sets the class's {anchorName ForM}`α` to be the same {anchorName ListForM}`α` found in the list:
```anchor ListForM
def List.forM [Monad m] : List α → (α → m PUnit) → m PUnit
| [], _ => pure ()
| x :: xs, action => do
action x
forM xs action
instance : ForM m (List α) α where
forM := List.forM
```
The {ref "reader-io-implementation"}[function {anchorName doList (module := DirTree)}`doList` from {lit}`doug`] is {anchorName ForM}`forM` for lists.
Because {anchorName countLettersForM}`forM` is intended to be used in {kw}`do`-blocks, it uses {anchorName ForM}`Monad` rather than {anchorName OptionTExec}`Applicative`.
{anchorName ForM}`forM` can be used to make {anchorName countLettersForM}`countLetters` much shorter:
```anchor countLettersForM
def countLetters (str : String) : StateT LetterCounts (Except Err) Unit :=
forM str.toList fun c => do
if c.isAlpha then
if vowels.contains c then
modify fun st => {st with vowels := st.vowels + 1}
else if consonants.contains c then
modify fun st => {st with consonants := st.consonants + 1}
else throw (.notALetter c)
```
The instance for {anchorName ManyForM}`Many` is very similar:
```anchor ManyForM
def Many.forM [Monad m] : Many α → (α → m PUnit) → m PUnit
| Many.none, _ => pure ()
| Many.more first rest, action => do
action first
forM (rest ()) action
instance : ForM m (Many α) α where
forM := Many.forM
```
Because {anchorName ForM}`γ` can be any type at all, {anchorName ForM}`ForM` can support non-polymorphic collections.
A very simple collection is one of the natural numbers less than some given number, in reverse order:
```anchor AllLessThan
structure AllLessThan where
num : Nat
```
Its {anchorName ForM}`ForM` operator applies the provided action to each smaller {anchorName ListCount}`Nat`:
```anchor AllLessThanForM
def AllLessThan.forM [Monad m]
(coll : AllLessThan) (action : Nat → m Unit) :
m Unit :=
let rec countdown : Nat → m Unit
| 0 => pure ()
| n + 1 => do
action n
countdown n
countdown coll.num
instance : ForM m AllLessThan Nat where
forM := AllLessThan.forM
```
Running {anchorName AllLessThanForMRun}`IO.println` on each number less than five can be accomplished with {anchorName ForM}`ForM`:
```anchor AllLessThanForMRun
#eval forM { num := 5 : AllLessThan } IO.println
```
```anchorInfo AllLessThanForMRun
4
3
2
1
0
```
An example {anchorName ForM}`ForM` instance that works only in a particular monad is one that loops over the lines read from an IO stream, such as standard input:
```anchor LinesOf (module := ForMIO)
structure LinesOf where
stream : IO.FS.Stream
partial def LinesOf.forM
(readFrom : LinesOf) (action : String → IO Unit) :
IO Unit := do
let line ← readFrom.stream.getLine
if line == "" then return ()
action line
forM readFrom action
instance : ForM IO LinesOf String where
forM := LinesOf.forM
```
The definition of {anchorName ForM}`ForM` is marked {kw}`partial` because there is no guarantee that the stream is finite.
In this case, {anchorName ranges}`IO.FS.Stream.getLine` works only in the {anchorName countToThree}`IO` monad, so no other monad can be used for looping.
This example program uses this looping construct to filter out lines that don't contain letters:
```anchor main (module := ForMIO)
def main (argv : List String) : IO UInt32 := do
if argv != [] then
IO.eprintln "Unexpected arguments"
return 1
forM (LinesOf.mk (← IO.getStdin)) fun line => do
if line.any (·.isAlpha) then
IO.print line
return 0
```
```commands formio "formio" (show := false)
$ ls
expected
test-data
$ cp ../ForMIO.lean .
$ ls
ForMIO.lean
expected
test-data
```
The file {lit}`test-data` contains:
```file formio "formio/test-data"
Hello!
!!!!!
12345
abc123
Ok
```
Invoking this program, which is stored in {lit}`ForMIO.lean`, yields the following output:
```commands formio "formio"
$ lean --run ForMIO.lean < test-data
Hello!
abc123
Ok
```
## Stopping Iteration
%%%
tag := "break"
%%%
Terminating a loop early is difficult to do with {anchorName ForM}`ForM`.
Writing a function that iterates over the {anchorName AllLessThan}`Nat`s in an {anchorName AllLessThan}`AllLessThan` only until {anchorTerm OptionTcountToThree}`3` is reached requires a means of stopping the loop partway through.
One way to achieve this is to use {anchorName ForM}`ForM` with the {anchorName OptionTExec}`OptionT` monad transformer.
The first step is to define {anchorName OptionTExec}`OptionT.exec`, which discards information about both the return value and whether or not the transformed computation succeeded:
```anchor OptionTExec
def OptionT.exec [Applicative m] (action : OptionT m α) : m Unit :=
action *> pure ()
```
Then, failure in the {anchorName OptionTExec}`OptionT` instance of {anchorName AlternativeOptionT (module:=Examples.MonadTransformers.Defs)}`Alternative` can be used to terminate looping early:
```anchor OptionTcountToThree
def countToThree (n : Nat) : IO Unit :=
let nums : AllLessThan := ⟨n⟩
OptionT.exec (forM nums fun i => do
if i < 3 then failure else IO.println i)
```
A quick test demonstrates that this solution works:
```anchor optionTCountSeven
#eval countToThree 7
```
```anchorInfo optionTCountSeven
6
5
4
3
```
However, this code is not so easy to read.
Terminating a loop early is a common task, and Lean provides more syntactic sugar to make this easier.
This same function can also be written as follows:
```anchor countToThree
def countToThree (n : Nat) : IO Unit := do
let nums : AllLessThan := ⟨n⟩
for i in nums do
if i < 3 then break
IO.println i
```
Testing it reveals that it works just like the prior version:
```anchor countSevenFor
#eval countToThree 7
```
```anchorInfo countSevenFor
6
5
4
3
```
The {kw}`for`{lit}` ...`{kw}`in`{lit}` ...`{kw}`do`{lit}` ...` syntax desugars to the use of a type class called {anchorName ForInIOAllLessThan}`ForIn`, which is a somewhat more complicated version of {anchorName ForM}`ForM` that keeps track of state and early termination.
The standard library provides an adapter that converts a {anchorName ForM}`ForM` instance into a {anchorName ForInIOAllLessThan}`ForIn` instance, called {anchorName ForInIOAllLessThan}`ForM.forIn`.
To enable {kw}`for` loops based on a {anchorName ForM}`ForM` instance, add something like the following, with appropriate replacements for {anchorName AllLessThan}`AllLessThan` and {anchorName AllLessThan}`Nat`:
```anchor ForInIOAllLessThan
instance : ForIn m AllLessThan Nat where
forIn := ForM.forIn
```
Note, however, that this adapter only works for {anchorName ForM}`ForM` instances that keep the monad unconstrained, as most of them do.
This is because the adapter uses {anchorName SomeMonads (module:=Examples.MonadTransformers.Defs)}`StateT` and {anchorName SomeMonads (module:=Examples.MonadTransformers.Defs)}`ExceptT`, rather than the underlying monad.
Early return is supported in {kw}`for` loops.
The translation of {kw}`do` blocks with early return into a use of an exception monad transformer applies equally well underneath {anchorName ForM}`ForM` as the earlier use of {anchorName OptionTExec}`OptionT` to halt iteration does.
This version of {anchorName findHuh}`List.find?` makes use of both:
```anchor findHuh
def List.find? (p : α → Bool) (xs : List α) : Option α := do
for x in xs do
if p x then return x
failure
```
In addition to {kw}`break`, {kw}`for` loops support {kw}`continue` to skip the rest of the loop body in an iteration.
An alternative (but confusing) formulation of {anchorName findHuhCont}`List.find?` skips elements that don't satisfy the check:
```anchor findHuhCont
def List.find? (p : α → Bool) (xs : List α) : Option α := do
for x in xs do
if not (p x) then continue
return x
failure
```
A {anchorName ranges}`Std.Range` is a structure that consists of a starting number, an ending number, and a step.
They represent a sequence of natural numbers, from the starting number to the ending number, increasing by the step each time.
Lean has special syntax to construct ranges, consisting of square brackets, numbers, and colons that comes in four varieties.
The stopping point must always be provided, while the start and the step are optional, defaulting to {anchorTerm ranges}`0` and {anchorTerm ranges}`1`, respectively:
:::table +header
*
* Expression
* Start
* Stop
* Step
* As List
*
* {anchorTerm rangeStopContents}`[:10]`
* {anchorTerm ranges}`0`
* {anchorTerm rangeStop}`10`
* {anchorTerm ranges}`1`
* {anchorInfo rangeStopContents}`[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`
*
* {anchorTerm rangeStartStopContents}`[2:10]`
* {anchorTerm rangeStartStopContents}`2`
* {anchorTerm rangeStartStopContents}`10`
* {anchorTerm ranges}`1`
* {anchorInfo rangeStartStopContents}`[2, 3, 4, 5, 6, 7, 8, 9]`
*
* {anchorTerm rangeStopStepContents}`[:10:3]`
* {anchorTerm ranges}`0`
* {anchorTerm rangeStartStopContents}`10`
* {anchorTerm rangeStopStepContents}`3`
* {anchorInfo rangeStopStepContents}`[0, 3, 6, 9]`
*
* {anchorTerm rangeStartStopStepContents}`[2:10:3]`
* {anchorTerm rangeStartStopStepContents}`2`
* {anchorTerm rangeStartStopStepContents}`10`
* {anchorTerm rangeStartStopStepContents}`3`
* {anchorInfo rangeStartStopStepContents}`[2, 5, 8]`
:::
Note that the starting number _is_ included in the range, while the stopping numbers is not.
All three arguments are {anchorName three}`Nat`s, which means that ranges cannot count down—a range where the starting number is greater than or equal to the stopping number simply contains no numbers.
Ranges can be used with {kw}`for` loops to draw numbers from the range.
This program counts even numbers from four to eight:
```anchor fourToEight
def fourToEight : IO Unit := do
for i in [4:9:2] do
IO.println i
```
Running it yields:
```anchorInfo fourToEightOut
4
6
8
```
Finally, {kw}`for` loops support iterating over multiple collections in parallel, by separating the {kw}`in` clauses with commas.
Looping halts when the first collection runs out of elements, so the declaration:
```anchor parallelLoop
def parallelLoop := do
for x in ["currant", "gooseberry", "rowan"], y in [4:8] do
IO.println (x, y)
```
produces three lines of output:
```anchor parallelLoopOut
#eval parallelLoop
```
```anchorInfo parallelLoopOut
(currant, 4)
(gooseberry, 5)
(rowan, 6)
```
Many data structures implement an enhanced version of the {anchorName ForInIOAllLessThan}`ForIn` type class that adds evidence that the element was drawn from the collection to the loop body.
These can be used by providing a name for the evidence prior to the name of the element.
This function prints all the elements of an array together with their indices, and the compiler is able to determine that the array lookups are all safe due to the evidence {anchorName printArray}`h`:
```anchor printArray
def printArray [ToString α] (xs : Array α) : IO Unit := do
for h : i in [0:xs.size] do
IO.println s!"{i}:\t{xs[i]}"
```
In this example, {anchorName printArray}`h` is evidence that {lit}`i ∈ [0:xs.size]`, and the tactic that checks whether {anchorTerm printArray}`xs[i]` is safe is able to transform this into evidence that {lit}`i < xs.size`.
# Mutable Variables
%%%
tag := "let-mut"
%%%
In addition to early {kw}`return`, {kw}`else`-less {kw}`if`, and {kw}`for` loops, Lean supports local mutable variables within a {kw}`do` block.
Behind the scenes, these mutable variables desugar to code that's equivalent to {anchorName twoStateT}`StateT`, rather than being implemented by true mutable variables.
Once again, functional programming is used to simulate imperative programming.
A local mutable variable is introduced with {kw}`let mut` instead of plain {kw}`let`.
The definition {anchorName two}`two`, which uses the identity monad {anchorName sameBlock}`Id` to enable {kw}`do`-syntax without introducing any effects, counts to {anchorTerm ranges}`2`:
```anchor two
def two : Nat := Id.run do
let mut x := 0
x := x + 1
x := x + 1
return x
```
This code is equivalent to a definition that uses {anchorName twoStateT}`StateT` to add {anchorTerm twoStateT}`1` twice:
```anchor twoStateT
def two : Nat :=
let block : StateT Nat Id Nat := do
modify (· + 1)
modify (· + 1)
return (← get)
let (result, _finalState) := block 0
result
```
Local mutable variables work well with all the other features of {kw}`do`-notation that provide convenient syntax for monad transformers.
The definition {anchorName three}`three` counts the number of entries in a three-entry list:
```anchor three
def three : Nat := Id.run do
let mut x := 0
for _ in [1, 2, 3] do
x := x + 1
return x
```
Similarly, {anchorName six}`six` adds the entries in a list:
```anchor six
def six : Nat := Id.run do
let mut x := 0
for y in [1, 2, 3] do
x := x + y
return x
```
{anchorName ListCount}`List.count` counts the number of entries in a list that satisfy some check:
```anchor ListCount
def List.count (p : α → Bool) (xs : List α) : Nat := Id.run do
let mut found := 0
for x in xs do
if p x then found := found + 1
return found
```
Local mutable variables can be more convenient to use and easier to read than an explicit local use of {anchorName twoStateT}`StateT`.
However, they don't have the full power of unrestricted mutable variables from imperative languages.
In particular, they can only be modified in the {kw}`do`-block in which they are introduced.
This means, for instance, that {kw}`for`-loops can't be replaced by otherwise-equivalent recursive helper functions.
This version of {anchorName nonLocalMut}`List.count`:
```anchor nonLocalMut
def List.count (p : α → Bool) (xs : List α) : Nat := Id.run do
let mut found := 0
let rec go : List α → Id Unit
| [] => pure ()
| y :: ys => do
if p y then found := found + 1
go ys
return found
```
yields the following error on the attempted mutation of {anchorName nonLocalMut}`found`:
```anchorError nonLocalMut
`found` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intend to mutate but define `found`, consider using `let found` instead
```
This is because the recursive function is written in the identity monad, and only the monad of the {kw}`do`-block in which the variable is introduced is transformed with {anchorName twoStateT}`StateT`.
# What counts as a {kw}`do` block?
%%%
tag := "do-block-boundaries"
%%%
Many features of {kw}`do`-notation apply only to a single {kw}`do`-block.
Early return terminates the current block, and mutable variables can only be mutated in the block that they are defined in.
To use them effectively, it's important to know what counts as “the same block”.
Generally speaking, the indented block following the {kw}`do` keyword counts as a block, and the immediate sequence of statements underneath it are part of that block.
Statements in independent blocks that are nonetheless contained in a block are not considered part of the block.
However, the rules that govern what exactly counts as the same block are slightly subtle, so some examples are in order.
The precise nature of the rules can be tested by setting up a program with a mutable variable and seeing where the mutation is allowed.
This program has a mutation that is clearly in the same block as the mutable variable:
```anchor sameBlock
example : Id Unit := do
let mut x := 0
x := x + 1
```
When a mutation occurs in a {kw}`do`-block that is part of a {kw}`let`-statement that defines a name using {lit}`:=`, then it is not considered to be part of the block:
```anchor letBodyNotBlock
example : Id Unit := do
let mut x := 0
let other := do
x := x + 1
other
```
```anchorError letBodyNotBlock
`x` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intend to mutate but define `x`, consider using `let x` instead
```
However, a {kw}`do`-block that occurs under a {kw}`let`-statement that defines a name using {lit}`←` is considered part of the surrounding block.
The following program is accepted:
```anchor letBodyArrBlock
example : Id Unit := do
let mut x := 0
let other ← do
x := x + 1
pure other
```
Similarly, {kw}`do`-blocks that occur as arguments to functions are independent of their surrounding blocks.
The following program is not accepted:
```anchor funArgNotBlock
example : Id Unit := do
let mut x := 0
let addFour (y : Id Nat) := Id.run y + 4
addFour do
x := 5
```
```anchorError funArgNotBlock
`x` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intend to mutate but define `x`, consider using `let x` instead
```
If the {kw}`do` keyword is completely redundant, then it does not introduce a new block.
This program is accepted, and is equivalent to the first one in this section:
```anchor collapsedBlock
example : Id Unit := do
let mut x := 0
do x := x + 1
```
The contents of branches under a {kw}`do` (such as those introduced by {kw}`match` or {kw}`if`) are considered to be part of the surrounding block, whether or not a redundant {kw}`do` is added.
The following programs are all accepted:
```anchor ifDoSame
example : Id Unit := do
let mut x := 0
if x > 2 then
x := x + 1
```
```anchor ifDoDoSame
example : Id Unit := do
let mut x := 0
if x > 2 then do
x := x + 1
```
```anchor matchDoSame
example : Id Unit := do
let mut x := 0
match true with
| true => x := x + 1
| false => x := 17
```
```anchor matchDoDoSame
example : Id Unit := do
let mut x := 0
match true with
| true => do
x := x + 1
| false => do
x := 17
```
Similarly, the {kw}`do` that occurs as part of the {kw}`for` and {kw}`unless` syntax is just part of their syntax, and does not introduce a fresh {kw}`do`-block.
These programs are also accepted:
```anchor doForSame
example : Id Unit := do
let mut x := 0
for y in [1:5] do
x := x + y
```
```anchor doUnlessSame
example : Id Unit := do
let mut x := 0
unless 1 < 5 do
x := x + 1
```
# Imperative or Functional Programming?
%%%
tag := none
%%%
The imperative features provided by Lean's {kw}`do`-notation allow many programs to very closely resemble their counterparts in languages like Rust, Java, or C#.
This resemblance is very convenient when translating an imperative algorithm into Lean, and some tasks are just most naturally thought of imperatively.
The introduction of monads and monad transformers enables imperative programs to be written in purely functional languages, and {kw}`do`-notation as a specialized syntax for monads (potentially locally transformed) allows functional programmers to have the best of both worlds: the strong reasoning principles afforded by immutability and a tight control over available effects through the type system are combined with syntax and libraries that allow programs that use effects to look familiar and be easy to read.
Monads and monad transformers allow functional versus imperative programming to be a matter of perspective.
# Exercises
%%%
tag := "monad-transformer-do-exercises"
%%%
* Rewrite {lit}`doug` to use {kw}`for` instead of the {anchorName doList (module:=DirTree)}`doList` function.
* Are there other opportunities to use the features introduced in this section to improve the code? If so, use them! |
fp-lean/book/FPLean/MonadTransformers/Transformers.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.MonadTransformers.Defs"
#doc (Manual) "A Monad Construction Kit" =>
{anchorName m}`ReaderT` is far from the only useful monad transformer.
This section describes a number of additional transformers.
Each monad transformer consists of the following:
1. A definition or datatype {anchorName general}`T` that takes a monad as an argument.
It should have a type like {anchorTerm general}`(Type u → Type v) → Type u → Type v`, though it may accept additional arguments prior to the monad.
2. A {anchorName general}`Monad` instance for {anchorTerm general}`T m` that relies on an instance of {anchorTerm general}`Monad m`. This enables the transformed monad to be used as a monad.
3. A {anchorName general}`MonadLift` instance that translates actions of type {anchorTerm general}`m α` into actions of type {anchorTerm general}`T m α`, for arbitrary monads {anchorName general}`m`. This enables actions from the underlying monad to be used in the transformed monad.
Furthermore, the {anchorName general}`Monad` instance for the transformer should obey the contract for {anchorName general}`Monad`, at least if the underlying {anchorName general}`Monad` instance does.
In addition, {anchorTerm general}`monadLift (pure x : m α)` should be equivalent to {anchorTerm general}`pure x` in the transformed monad, and {anchorName general}`monadLift` should distribute over {anchorName MonadStateT}`bind` so that {anchorTerm general}`monadLift (x >>= f : m α)` is the same as {anchorTerm general}`(monadLift x : m α) >>= fun y => monadLift (f y)`.
Many monad transformers additionally define type classes in the style of {anchorName m}`MonadReader` that describe the actual effects available in the monad.
This can provide more flexibility: it allows programs to be written that rely only on an interface, and don't constrain the underlying monad to be implemented by a given transformer.
The type classes are a way for programs to express their requirements, and monad transformers are a convenient way to meet these requirements.
# Failure with {lit}`OptionT`
%%%
tag := "OptionT"
%%%
Failure, represented by the {anchorName OptionExcept}`Option` monad, and exceptions, represented by the {anchorName M1eval}`Except` monad, both have corresponding transformers.
In the case of {anchorName OptionTdef}`Option`, failure can be added to a monad by having it contain values of type {anchorTerm OptionTdef}`Option α` where it would otherwise contain values of type {anchorName OptionTdef}`α`.
For example, {anchorTerm m}`IO (Option α)` represents {anchorName m}`IO` actions that don't always return a value of type {anchorName m}`α`.
This suggests the definition of the monad transformer {anchorName OptionTdef}`OptionT`:
```anchor OptionTdef
def OptionT (m : Type u → Type v) (α : Type u) : Type v :=
m (Option α)
```
As an example of {anchorName OptionTdef}`OptionT` in action, consider a program that asks the user questions.
The function {anchorName getSomeInput}`getSomeInput` asks for a line of input and removes whitespace from both ends.
If the resulting trimmed input is non-empty, then it is returned, but the function fails if there are no non-whitespace characters:
```anchor getSomeInput
def getSomeInput : OptionT IO String := do
let input ← (← IO.getStdin).getLine
let trimmed := input.trim
if trimmed == "" then
failure
else pure trimmed
```
This particular application tracks users with their name and their favorite species of beetle:
```anchor UserInfo
structure UserInfo where
name : String
favoriteBeetle : String
```
Asking the user for input is no more verbose than a function that uses only {anchorName m}`IO` would be:
```anchor getUserInfo
def getUserInfo : OptionT IO UserInfo := do
IO.println "What is your name?"
let name ← getSomeInput
IO.println "What is your favorite species of beetle?"
let beetle ← getSomeInput
pure ⟨name, beetle⟩
```
However, because the function runs in an {anchorTerm getSomeInput}`OptionT IO` context rather than just in {anchorName m}`IO`, failure in the first call to {anchorName getSomeInput}`getSomeInput` causes the whole {anchorName getUserInfo}`getUserInfo` to fail, with control never reaching the question about beetles.
The main function, {anchorName interact}`interact`, invokes {anchorName interact}`getUserInfo` in a purely {anchorName m}`IO` context, which allows it to check whether the call succeeded or failed by matching on the inner {anchorName m}`Option`:
```anchor interact
def interact : IO Unit := do
match ← getUserInfo with
| none =>
IO.eprintln "Missing info"
| some ⟨name, beetle⟩ =>
IO.println s!"Hello {name}, whose favorite beetle is {beetle}."
```
## The Monad Instance
%%%
tag := "OptionT-monad-instance"
%%%
Writing the monad instance reveals a difficulty.
Based on the types, {anchorName MonadExceptT}`pure` should use {anchorName MonadMissingUni}`pure` from the underlying monad {anchorName firstMonadOptionT}`m` together with {anchorName firstMonadOptionT}`some`.
Just as {anchorName firstMonadOptionT}`bind` for {anchorName m}`Option` branches on the first argument, propagating {anchorName firstMonadOptionT}`none`, {anchorName firstMonadOptionT}`bind` for {anchorName firstMonadOptionT}`OptionT` should run the monadic action that makes up the first argument, branch on the result, and then propagate {anchorName firstMonadOptionT}`none`.
Following this sketch yields the following definition, which Lean does not accept:
```anchor firstMonadOptionT
instance [Monad m] : Monad (OptionT m) where
pure x := pure (some x)
bind action next := do
match (← action) with
| none => pure none
| some v => next v
```
The error message shows a cryptic type mismatch:
```anchorError firstMonadOptionT
Application type mismatch: The argument
some x
has type
Option α✝
but is expected to have type
α✝
in the application
pure (some x)
```
The problem here is that Lean is selecting the wrong {anchorName firstMonadOptionT}`Monad` instance for the surrounding use of {anchorName firstMonadOptionT}`pure`.
Similar errors occur for the definition of {anchorName firstMonadOptionT}`bind`.
One solution is to use type annotations to guide Lean to the correct {anchorName MonadOptionTAnnots}`Monad` instance:
```anchor MonadOptionTAnnots
instance [Monad m] : Monad (OptionT m) where
pure x := (pure (some x) : m (Option _))
bind action next := (do
match (← action) with
| none => pure none
| some v => next v : m (Option _))
```
While this solution works, it is inelegant and the code becomes a bit noisy.
An alternative solution is to define functions whose type signatures guide Lean to the correct instances.
In fact, {anchorName OptionTStructure}`OptionT` could have been defined as a structure:
```anchor OptionTStructure
structure OptionT (m : Type u → Type v) (α : Type u) : Type v where
run : m (Option α)
```
This would solve the problem, because the constructor {anchorName OptionTStructuredefs}`OptionT.mk` and the field accessor {anchorName OptionTStructuredefs}`OptionT.run` would guide type class inference to the correct instances.
The downside to doing this is that the resulting code is more complicated, and these structures can make it more difficult to read proofs.
The best of both worlds can be achieved by defining functions that serve the same role as the constructor {anchorName OptionTStructuredefs}`OptionT.mk` and the field {anchorName OptionTStructuredefs}`OptionT.run`, but that work with the direct definition:
```anchor FakeStructOptionT
def OptionT.mk (x : m (Option α)) : OptionT m α := x
def OptionT.run (x : OptionT m α) : m (Option α) := x
```
Both functions return their inputs unchanged, but they indicate the boundary between code that is intended to present the interface of {anchorName FakeStructOptionT}`OptionT` and code that is intended to present the interface of the underlying monad {anchorName FakeStructOptionT}`m`.
Using these helpers, the {anchorName MonadOptionTFakeStruct}`Monad` instance becomes more readable:
```anchor MonadOptionTFakeStruct
instance [Monad m] : Monad (OptionT m) where
pure x := OptionT.mk (pure (some x))
bind action next := OptionT.mk do
match ← action with
| none => pure none
| some v => next v
```
Here, the use of {anchorName FakeStructOptionT}`OptionT.mk` indicates that its arguments should be considered as code that uses the interface of {anchorName MonadOptionTFakeStruct}`m`, which allows Lean to select the correct {anchorName MonadOptionTFakeStruct}`Monad` instances.
After defining the monad instance, it's a good idea to check that the monad contract is satisfied.
The first step is to show that {anchorTerm OptionTFirstLaw}`bind (pure v) f` is the same as {anchorTerm OptionTFirstLaw}`f v`.
Here's the steps:
```anchorEqSteps OptionTFirstLaw
bind (pure v) f
={ /-- Unfolding the definitions of `bind` and `pure` -/
by simp [bind, pure, OptionT.mk]
}=
OptionT.mk do
match ← pure (some v) with
| none => pure none
| some x => f x
={
/-- Desugaring nested action syntax -/
}=
OptionT.mk do
let y ← pure (some v)
match y with
| none => pure none
| some x => f x
={
/-- Desugaring `do`-notation -/
}=
OptionT.mk
(pure (some v) >>= fun y =>
match y with
| none => pure none
| some x => f x)
={
/-- Using the first monad rule for `m` -/
by simp [LawfulMonad.pure_bind (m := m)]
}=
OptionT.mk
(match some v with
| none => pure none
| some x => f x)
={
/-- Reduce `match` -/
}=
OptionT.mk (f v)
={
/-- Definition of `OptionT.mk` -/
}=
f v
```
The second rule states that {anchorTerm OptionTSecondLaw}`bind w pure` is the same as {anchorName OptionTSecondLaw}`w`.
To demonstrate this, unfold the definitions of {anchorName OptionTSecondLaw}`bind` and {anchorName OptionTSecondLaw}`pure`, yielding:
```anchorTerm OptionTSecondLaw
OptionT.mk do
match ← w with
| none => pure none
| some v => pure (some v)
```
In this pattern match, the result of both cases is the same as the pattern being matched, just with {anchorName OptionTSecondLaw}`pure` around it.
In other words, it is equivalent to {anchorTerm OptionTSecondLaw}`w >>= fun y => pure y`, which is an instance of {anchorName OptionTFirstLaw}`m`'s second monad rule.
The final rule states that {anchorTerm OptionTThirdLaw}`bind (bind v f) g` is the same as {anchorTerm OptionTThirdLaw}`bind v (fun x => bind (f x) g)`.
It can be checked in the same way, by expanding the definitions of {anchorName OptionTThirdLaw}`bind` and {anchorName OptionTSecondLaw}`pure` and then delegating to the underlying monad {anchorName OptionTFirstLaw}`m`.
## An {lit}`Alternative` Instance
%%%
tag := "OptionT-Alternative-instance"
%%%
One convenient way to use {anchorName OptionTdef}`OptionT` is through the {anchorName AlternativeOptionT}`Alternative` type class.
Successful return is already indicated by {anchorName AlternativeOptionT}`pure`, and the {anchorName AlternativeOptionT}`failure` and {anchorName AlternativeOptionT}`orElse` methods of {anchorName AlternativeOptionT}`Alternative` provide a way to write a program that returns the first successful result from a number of subprograms:
```anchor AlternativeOptionT
instance [Monad m] : Alternative (OptionT m) where
failure := OptionT.mk (pure none)
orElse x y := OptionT.mk do
match ← x with
| some result => pure (some result)
| none => y ()
```
## Lifting
%%%
tag := "OptionT-lifting"
%%%
Lifting an action from {anchorName LiftOptionT}`m` to {anchorTerm LiftOptionT}`OptionT m` only requires wrapping {anchorName LiftOptionT}`some` around the result of the computation:
```anchor LiftOptionT
instance [Monad m] : MonadLift m (OptionT m) where
monadLift action := OptionT.mk do
pure (some (← action))
```
# Exceptions
%%%
tag := "exceptions"
%%%
The monad transformer version of {anchorName ExceptT}`Except` is very similar to the monad transformer version of {anchorName m}`Option`.
Adding exceptions of type {anchorName ExceptT}`ε` to some monadic action of type {anchorTerm ExceptT}`m`{lit}` `{anchorTerm ExceptT}`α` can be accomplished by adding exceptions to {anchorName MonadExcept}`α`, yielding type {anchorTerm ExceptT}`m (Except ε α)`:
```anchor ExceptT
def ExceptT (ε : Type u) (m : Type u → Type v) (α : Type u) : Type v :=
m (Except ε α)
```
{anchorName OptionTdef}`OptionT` provides {anchorName FakeStructOptionT}`OptionT.mk` and {anchorName FakeStructOptionT}`OptionT.run` functions to guide the type checker towards the correct {anchorName MonadOptionTFakeStruct}`Monad` instances.
This trick is also useful for {anchorName ExceptTFakeStruct}`ExceptT`:
```anchor ExceptTFakeStruct
def ExceptT.mk {ε α : Type u} (x : m (Except ε α)) : ExceptT ε m α := x
def ExceptT.run {ε α : Type u} (x : ExceptT ε m α) : m (Except ε α) := x
```
The {anchorName MonadExceptT}`Monad` instance for {anchorName MonadExceptT}`ExceptT` is also very similar to the instance for {anchorName MonadOptionTFakeStruct}`OptionT`.
The only difference is that it propagates a specific error value, rather than {anchorName MonadOptionTFakeStruct}`none`:
```anchor MonadExceptT
instance {ε : Type u} {m : Type u → Type v} [Monad m] :
Monad (ExceptT ε m) where
pure x := ExceptT.mk (pure (Except.ok x))
bind result next := ExceptT.mk do
match ← result with
| .error e => pure (.error e)
| .ok x => next x
```
The type signatures of {anchorName ExceptTFakeStruct}`ExceptT.mk` and {anchorName ExceptTFakeStruct}`ExceptT.run` contain a subtle detail: they annotate the universe levels of {anchorName ExceptTFakeStruct}`α` and {anchorName ExceptTFakeStruct}`ε` explicitly.
If they are not explicitly annotated, then Lean generates a more general type signature in which they have distinct polymorphic universe variables.
However, the definition of {anchorName ExceptTFakeStruct}`ExceptT` expects them to be in the same universe, because they can both be provided as arguments to {anchorName ExceptTFakeStruct}`m`.
This can lead to a problem in the {anchorName MonadStateT}`Monad` instance where the universe level solver fails to find a working solution:
```anchor ExceptTNoUnis
def ExceptT.mk (x : m (Except ε α)) : ExceptT ε m α := x
```
```anchor MonadMissingUni
instance {ε : Type u} {m : Type u → Type v} [Monad m] :
Monad (ExceptT ε m) where
pure x := ExceptT.mk (pure (Except.ok x))
bind result next := ExceptT.mk do
match (← result) with
| .error e => pure (.error e)
| .ok x => next x
```
```anchorError MonadMissingUni
stuck at solving universe constraint
max ?u.10439 ?u.10440 =?= u
while trying to unify
ExceptT ε m β✝ : Type v
with
ExceptT.{max ?u.10440 ?u.10439, v} ε m β✝ : Type v
```
This kind of error message is typically caused by underconstrained universe variables.
Diagnosing it can be tricky, but a good first step is to look for reused universe variables in some definitions that are not reused in others.
Unlike {anchorName m}`Option`, the {anchorName m}`Except` datatype is typically not used as a data structure.
It is always used as a control structure with its {anchorName MonadExceptT}`Monad` instance.
This means that it is reasonable to lift {anchorTerm ExceptTLiftExcept}`Except ε` actions into {anchorTerm ExceptTLiftExcept}`ExceptT ε m`, as well as actions from the underlying monad {anchorName ExceptTLiftExcept}`m`.
Lifting {anchorName ExceptTLiftExcept}`Except` actions into {anchorName ExceptTLiftExcept}`ExceptT` actions is done by wrapping them in {anchorName ExceptTLiftExcept}`m`'s {anchorName ExceptTLiftExcept}`pure`, because an action that only has exception effects cannot have any effects from the monad {anchorName ExceptTLiftExcept}`m`:
```anchor ExceptTLiftExcept
instance [Monad m] : MonadLift (Except ε) (ExceptT ε m) where
monadLift action := ExceptT.mk (pure action)
```
Because actions from {anchorName ExceptTLiftExcept}`m` do not have any exceptions in them, their value should be wrapped in {anchorName MonadExceptT}`Except.ok`.
This can be accomplished using the fact that {anchorName various}`Functor` is a superclass of {anchorName various}`Monad`, so applying a function to the result of any monadic computation can be accomplished using {anchorName various}`Functor.map`:
```anchor ExceptTLiftM
instance [Monad m] : MonadLift m (ExceptT ε m) where
monadLift action := ExceptT.mk (.ok <$> action)
```
## Type Classes for Exceptions
%%%
tag := "exceptions-type-classes"
%%%
Exception handling fundamentally consists of two operations: the ability to throw exceptions, and the ability to recover from them.
Thus far, this has been accomplished using the constructors of {anchorName m}`Except` and pattern matching, respectively.
However, this ties a program that uses exceptions to one specific encoding of the exception handling effect.
Using a type class to capture these operations allows a program that uses exceptions to be used in _any_ monad that supports throwing and catching.
Throwing an exception should take an exception as an argument, and it should be allowed in any context where a monadic action is requested.
The “any context” part of the specification can be written as a type by writing {anchorTerm MonadExcept}`m α`—because there's no way to produce a value of any arbitrary type, the {anchorName MonadExcept}`throw` operation must be doing something that causes control to leave that part of the program.
Catching an exception should accept any monadic action together with a handler, and the handler should explain how to get back to the action's type from an exception:
```anchor MonadExcept
class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where
throw : ε → m α
tryCatch : m α → (ε → m α) → m α
```
The universe levels on {anchorName MonadExcept}`MonadExcept` differ from those of {anchorName ExceptT}`ExceptT`.
In {anchorName ExceptT}`ExceptT`, both {anchorName ExceptT}`ε` and {anchorName ExceptT}`α` have the same level, while {anchorName MonadExcept}`MonadExcept` imposes no such limitation.
This is because {anchorName MonadExcept}`MonadExcept` never places an exception value inside of {anchorName MonadExcept}`m`.
The most general universe signature recognizes the fact that {anchorName MonadExcept}`ε` and {anchorName MonadExcept}`α` are completely independent in this definition.
Being more general means that the type class can be instantiated for a wider variety of types.
An example program that uses {anchorName MonadExcept}`MonadExcept` is a simple division service.
The program is divided into two parts: a frontend that supplies a user interface based on strings that handles errors, and a backend that actually does the division.
Both the frontend and the backend can throw exceptions, the former for ill-formed input and the latter for division by zero errors.
The exceptions are an inductive type:
```anchor ErrEx
inductive Err where
| divByZero
| notANumber : String → Err
```
The backend checks for zero, and divides if it can:
```anchor divBackend
def divBackend [Monad m] [MonadExcept Err m] (n k : Int) : m Int :=
if k == 0 then
throw .divByZero
else pure (n / k)
```
The frontend's helper {anchorName asNumber}`asNumber` throws an exception if the string it is passed is not a number.
The overall frontend converts its inputs to {anchorName asNumber}`Int`s and calls the backend, handling exceptions by returning a friendly string error:
```anchor asNumber
def asNumber [Monad m] [MonadExcept Err m] (s : String) : m Int :=
match s.toInt? with
| none => throw (.notANumber s)
| some i => pure i
```
```anchor divFrontend
def divFrontend [Monad m] [MonadExcept Err m] (n k : String) : m String :=
tryCatch (do pure (toString (← divBackend (← asNumber n) (← asNumber k))))
fun
| .divByZero => pure "Division by zero!"
| .notANumber s => pure s!"Not a number: \"{s}\""
```
Throwing and catching exceptions is common enough that Lean provides a special syntax for using {anchorName divFrontendSugary}`MonadExcept`.
Just as {lit}`+` is short for {anchorName various}`HAdd.hAdd`, {kw}`try` and {kw}`catch` can be used as shorthand for the {anchorName MonadExcept}`tryCatch` method:
```anchor divFrontendSugary
def divFrontend [Monad m] [MonadExcept Err m] (n k : String) : m String :=
try
pure (toString (← divBackend (← asNumber n) (← asNumber k)))
catch
| .divByZero => pure "Division by zero!"
| .notANumber s => pure s!"Not a number: \"{s}\""
```
In addition to {anchorName m}`Except` and {anchorName ExceptT}`ExceptT`, there are useful {anchorName MonadExcept}`MonadExcept` instances for other types that may not seem like exceptions at first glance.
For example, failure due to {anchorName m}`Option` can be seen as throwing an exception that contains no data whatsoever, so there is an instance of {anchorTerm OptionExcept}`MonadExcept Unit Option` that allows {kw}`try`{lit}` ...`{kw}`catch`{lit}` ...` syntax to be used with {anchorName m}`Option`.
# State
%%%
tag := "state-monad"
%%%
A simulation of mutable state is added to a monad by having monadic actions accept a starting state as an argument and return a final state together with their result.
The bind operator for a state monad provides the final state of one action as an argument to the next action, threading the state through the program.
This pattern can also be expressed as a monad transformer:
```anchor DefStateT
def StateT (σ : Type u)
(m : Type u → Type v) (α : Type u) : Type (max u v) :=
σ → m (α × σ)
```
Once again, the monad instance is very similar to that for {anchorName State (module := Examples.Monads)}`State`.
The only difference is that the input and output states are passed around and returned in the underlying monad, rather than with pure code:
```anchor MonadStateT
instance [Monad m] : Monad (StateT σ m) where
pure x := fun s => pure (x, s)
bind result next := fun s => do
let (v, s') ← result s
next v s'
```
The corresponding type class has {anchorName MonadState}`get` and {anchorName MonadState}`set` methods.
One downside of {anchorName MonadState}`get` and {anchorName MonadState}`set` is that it becomes too easy to {anchorName MonadState}`set` the wrong state when updating it.
This is because retrieving the state, updating it, and saving the updated state is a natural way to write some programs.
For example, the following program counts the number of diacritic-free English vowels and consonants in a string of letters:
```anchor countLetters
structure LetterCounts where
vowels : Nat
consonants : Nat
deriving Repr
inductive Err where
| notALetter : Char → Err
deriving Repr
def vowels :=
let lowerVowels := "aeiuoy"
lowerVowels ++ lowerVowels.map (·.toUpper)
def consonants :=
let lowerConsonants := "bcdfghjklmnpqrstvwxz"
lowerConsonants ++ lowerConsonants.map (·.toUpper )
def countLetters (str : String) : StateT LetterCounts (Except Err) Unit :=
let rec loop (chars : List Char) := do
match chars with
| [] => pure ()
| c :: cs =>
let st ← get
let st' ←
if c.isAlpha then
if vowels.contains c then
pure {st with vowels := st.vowels + 1}
else if consonants.contains c then
pure {st with consonants := st.consonants + 1}
else -- modified or non-English letter
pure st
else throw (.notALetter c)
set st'
loop cs
loop str.toList
```
It would be very easy to write {lit}`set st` instead of {anchorTerm countLetters}`set st'`.
In a large program, this kind of mistake can lead to difficult-to-diagnose bugs.
While using a nested action for the call to {anchorName countLetters}`get` would solve this problem, it can't solve all such problems.
For example, a function might update a field on a structure based on the values of two other fields.
This would require two separate nested-action calls to {anchorName countLetters}`get`.
Because the Lean compiler contains optimizations that are only effective when there is a single reference to a value, duplicating the references to the state might lead to code that is significantly slower.
Both the potential performance problem and the potential bug can be worked around by using {anchorName countLettersModify}`modify`, which transforms the state using a function:
```anchor countLettersModify
def countLetters (str : String) : StateT LetterCounts (Except Err) Unit :=
let rec loop (chars : List Char) := do
match chars with
| [] => pure ()
| c :: cs =>
if c.isAlpha then
if vowels.contains c then
modify fun st => {st with vowels := st.vowels + 1}
else if consonants.contains c then
modify fun st => {st with consonants := st.consonants + 1}
else -- modified or non-English letter
pure ()
else throw (.notALetter c)
loop cs
loop str.toList
```
The type class contains a function akin to {anchorName modify}`modify` called {anchorName modify}`modifyGet`, which allows the function to both compute a return value and transform an old state in a single step.
The function returns a pair in which the first element is the return value, and the second element is the new state; {anchorName modify}`modify` just adds the constructor of {anchorName modify}`Unit` to the pair used in {anchorName modify}`modifyGet`:
```anchor modify
def modify [MonadState σ m] (f : σ → σ) : m Unit :=
modifyGet fun s => ((), f s)
```
The definition of {anchorName MonadState}`MonadState` is as follows:
```anchor MonadState
class MonadState (σ : outParam (Type u)) (m : Type u → Type v) :
Type (max (u+1) v) where
get : m σ
set : σ → m PUnit
modifyGet : (σ → α × σ) → m α
```
{anchorName MonadState}`PUnit` is a version of the {anchorName modify}`Unit` type that is universe-polymorphic to allow it to be in {anchorTerm MonadState}`Type u` instead of {anchorTerm MonadState}`Type`.
While it would be possible to provide a default implementation of {anchorName MonadState}`modifyGet` in terms of {anchorName MonadState}`get` and {anchorName MonadState}`set`, it would not admit the optimizations that make {anchorName MonadState}`modifyGet` useful in the first place, rendering the method useless.
# {lit}`Of` Classes and {lit}`The` Functions
%%%
tag := "of-and-the"
%%%
Thus far, each monad type class that takes extra information, like the type of exceptions for {anchorName MonadExcept}`MonadExcept` or the type of the state for {anchorName MonadState}`MonadState`, has this type of extra information as an output parameter.
For simple programs, this is generally convenient, because a monad that combines one use each of {anchorName MonadStateT}`StateT`, {anchorName m}`ReaderT`, and {anchorName ExceptT}`ExceptT` has only a single state type, environment type, and exception type.
As monads grow in complexity, however, they may involve multiple states or errors types.
In this case, the use of an output parameter makes it impossible to target both states in the same {kw}`do`-block.
For these cases, there are additional type classes in which the extra information is not an output parameter.
These versions of the type classes use the word {lit}`Of` in the name.
For example, {anchorName getTheType}`MonadStateOf` is like {anchorName MonadState}`MonadState`, but without an {anchorName MonadState}`outParam` modifier.
Instead of an {anchorName MonadState}`outParam`, these classes use a {anchorName various}`semiOutParam` for their respective state, environment, or exception types.
Like an {anchorName MonadState}`outParam`, a {anchorName various}`semiOutParam` is not required be known before Lean begins the process of searching for an instance.
However, there is an important difference: {anchorName MonadState}`outParam`s are ignored during the search for an instance, and as a result they are truly outputs.
If an {anchorName MonadState}`outParam` is known prior to the search, then Lean merely checks that the result of the search is the same as what was known.
On the other hand, a {anchorName various}`semiOutParam` that is known prior to the start of the search can be used to narrow down candidates, just like an input parameter.
When a state monad's state type is an {anchorName MonadState}`outParam`, then each monad can have at most one type of state.
This is convenient, because it improves type inference: the state type can be inferred in more circumstances.
This is also inconvenient, because a monad built from multiple uses of {anchorName countLetters}`StateT` cannot provide a useful {anchorName modify}`MonadState` instance.
Using {anchorName modifyTheType}`MonadStateOf`, however, causes Lean to take the state type into account when it is available to select which instance to use, so one monad may provide multiple types of state.
The downside of this is that the resulting instance may not be the one that was intended when the state type has not been specified explicitly enough, which can lead to confusing error messages.
Similarly, there are versions of the type class methods that accept the type of the extra information as an _explicit_, rather than implicit, argument.
For {anchorName modifyTheType}`MonadStateOf`, there are {anchorTerm getTheType}`getThe` with type
```anchorTerm getTheType
(σ : Type u) → {m : Type u → Type v} → [MonadStateOf σ m] → m σ
```
and {anchorTerm modifyTheType}`modifyThe` with type
```anchorTerm modifyTheType
(σ : Type u) → {m : Type u → Type v} → [MonadStateOf σ m] → (σ → σ) → m PUnit
```
There is no {lit}`setThe` because the type of the new state is enough to decide which surrounding state monad transformer to use.
In the Lean standard library, there are instances of the non-{lit}`Of` versions of the classes defined in terms of the instances of the versions with {lit}`Of`.
In other words, implementing the {lit}`Of` version yields implementations of both.
It's generally a good idea to implement the {lit}`Of` version, and then start writing programs using the non-{lit}`Of` versions of the class, transitioning to the {lit}`Of` version if the output parameter becomes inconvenient.
# Transformers and {lit}`Id`
%%%
tag := "transformers-and-Id"
%%%
The identity monad {anchorName various}`Id` is the monad that has no effects whatsoever, to be used in contexts that expect a monad for some reason but where none is actually necessary.
Another use of {anchorName various}`Id` is to serve as the bottom of a stack of monad transformers.
For instance, {anchorTerm StateTDoubleB}`StateT σ Id` works just like {anchorTerm set (module:=Examples.Monads)}`State σ`.
# Exercises
%%%
tag := "monad-transformer-exercises"
%%%
## Monad Contract
%%%
tag := none
%%%
Using pencil and paper, check that the rules of the monad transformer contract are satisfied for each monad transformer in this section.
## Logging Transformer
%%%
tag := none
%%%
Define a monad transformer version of {anchorName WithLog (module:=Examples.Monads)}`WithLog`.
Also define the corresponding type class {lit}`MonadWithLog`, and write a program that combines logging and exceptions.
## Counting Files
%%%
tag := none
%%%
Modify {lit}`doug`'s monad with {anchorName MonadStateT}`StateT` such that it counts the number of directories and files seen.
At the end of execution, it should display a report like:
```
Viewed 38 files in 5 directories.
``` |
fp-lean/book/FPLean/FunctorApplicativeMonad/Complete.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.FunctorApplicativeMonad.ActualDefs"
#doc (Manual) "The Complete Definitions" =>
%%%
tag := "complete-definitions"
%%%
Now that all the relevant language features have been presented, this section describes the complete, honest definitions of {anchorName HonestFunctor}`Functor`, {anchorName Applicative}`Applicative`, and {anchorName Monad}`Monad` as they occur in the Lean standard library.
For the sake of understanding, no details are omitted.
# Functor
%%%
tag := "complete-functor-definition"
%%%
The complete definition of the {anchorName Applicative}`Functor` class makes use of universe polymorphism and a default method implementation:
```anchor HonestFunctor
class Functor (f : Type u → Type v) : Type (max (u+1) v) where
map : {α β : Type u} → (α → β) → f α → f β
mapConst : {α β : Type u} → α → f β → f α :=
Function.comp map (Function.const _)
```
In this definition, {anchorName HonestFunctor}`Function.comp` is function composition, which is typically written with the {lit}`∘` operator.
{anchorName HonestFunctor}`Function.const` is the _constant function_, which is a two-argument function that ignores its second argument.
Applying this function to only one argument produces a function that always returns the same value, which is useful when an API demands a function but a program doesn't need to compute different results for different arguments.
A simple version of {anchorName HonestFunctor}`Function.const` can be written as follows:
```anchor simpleConst
def simpleConst (x : α) (_ : β) : α := x
```
Using it with one argument as the function argument to {anchorTerm extras}`List.map` demonstrates its utility:
```anchor mapConst
#eval [1, 2, 3].map (simpleConst "same")
```
```anchorInfo mapConst
["same", "same", "same"]
```
The actual function has the following signature:
```anchorInfo FunctionConstType
Function.const.{u, v} {α : Sort u} (β : Sort v) (a : α) : β → α
```
Here, the type argument {anchorName HonestFunctor}`β` is an explicit argument, so the default definition of {anchorName HonestFunctor}`mapConst` provides an {anchorTerm HonestFunctor}`_` argument that instructs Lean to find a unique type to pass to {anchorName HonestFunctor}`Function.const` that would cause the program to type check.
{anchorTerm unfoldCompConst}`Function.comp map (Function.const _)` is equivalent to {anchorTerm unfoldCompConst}`fun (x : α) (y : f β) => map (fun _ => x) y`.
The {anchorName HonestFunctor}`Functor` type class inhabits a universe that is the greater of {anchorTerm HonestFunctor}`u+1` and {anchorTerm HonestFunctor}`v`.
Here, {anchorTerm HonestFunctor}`u` is the level of universes accepted as arguments to {anchorName HonestFunctor}`f`, while {anchorTerm HonestFunctor}`v` is the universe returned by {anchorName HonestFunctor}`f`.
To see why the structure that implements the {anchorName HonestFunctor}`Functor` type class must be in a universe that's larger than {anchorTerm HonestFunctor}`u`, begin with a simplified definition of the class:
```anchor FunctorSimplified
class Functor (f : Type u → Type v) : Type (max (u+1) v) where
map : {α β : Type u} → (α → β) → f α → f β
```
This type class's structure type is equivalent to the following inductive type:
```anchor FunctorDatatype
inductive Functor (f : Type u → Type v) : Type (max (u+1) v) where
| mk : ({α β : Type u} → (α → β) → f α → f β) → Functor f
```
The implementation of the {lit}`map` method that is passed as an argument to {anchorName FunctorDatatype}`mk` contains a function that takes two types in {anchorTerm FunctorDatatype}`Type u` as arguments.
This means that the type of the function itself is in {lit}`Type (u+1)`, so {anchorName FunctorDatatype}`Functor` must also be at a level that is at least {anchorTerm FunctorDatatype}`u+1`.
Similarly, other arguments to the function have a type built by applying {anchorName FunctorDatatype}`f`, so it must also have a level that is at least {anchorTerm FunctorDatatype}`v`.
All the type classes in this section share this property.
# Applicative
%%%
tag := "complete-applicative-definition"
%%%
The {anchorName Applicative}`Applicative` type class is actually built from a number of smaller classes that each contain some of the relevant methods.
The first are {anchorName Applicative}`Pure` and {anchorName Applicative}`Seq`, which contain {anchorName Applicative}`pure` and {anchorName Seq}`seq` respectively:
```anchor Pure
class Pure (f : Type u → Type v) : Type (max (u+1) v) where
pure {α : Type u} : α → f α
```
```anchor Seq
class Seq (f : Type u → Type v) : Type (max (u+1) v) where
seq : {α β : Type u} → f (α → β) → (Unit → f α) → f β
```
In addition to these, {anchorName Applicative}`Applicative` also depends on {anchorName SeqRight}`SeqRight` and an analogous {anchorName SeqLeft}`SeqLeft` class:
```anchor SeqRight
class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where
seqRight : {α β : Type u} → f α → (Unit → f β) → f β
```
```anchor SeqLeft
class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where
seqLeft : {α β : Type u} → f α → (Unit → f β) → f α
```
The {anchorName SeqRight}`seqRight` function, which was introduced in the {ref "alternative"}[section about alternatives and validation], is easiest to understand from the perspective of effects.
{anchorTerm seqRightSugar (module := Examples.FunctorApplicativeMonad)}`E1 *> E2`, which desugars to {anchorTerm seqRightSugar (module := Examples.FunctorApplicativeMonad)}`SeqRight.seqRight E1 (fun () => E2)`, can be understood as first executing {anchorName seqRightSugar (module:=Examples.FunctorApplicativeMonad)}`E1`, and then {anchorName seqRightSugar (module:=Examples.FunctorApplicativeMonad)}`E2`, resulting only in {anchorName seqRightSugar (module:=Examples.FunctorApplicativeMonad)}`E2`'s result.
Effects from {anchorName seqRightSugar (module:=Examples.FunctorApplicativeMonad)}`E1` may result in {anchorName seqRightSugar (module:=Examples.FunctorApplicativeMonad)}`E2` not being run, or being run multiple times.
Indeed, if {anchorName SeqRight}`f` has a {anchorName Monad}`Monad` instance, then {anchorTerm seqRightSugar (module:=Examples.FunctorApplicativeMonad)}`E1 *> E2` is equivalent to {lit}`do let _ ← E1; E2`, but {anchorName SeqRight}`seqRight` can be used with types like {anchorName Validate (module:=Examples.FunctorApplicativeMonad)}`Validate` that are not monads.
Its cousin {anchorName SeqLeft}`seqLeft` is very similar, except the leftmost expression's value is returned.
{anchorTerm seqLeftSugar}`E1 <* E2` desugars to {anchorTerm seqLeftSugar}`SeqLeft.seqLeft E1 (fun () => E2)`.
{anchorTerm seqLeftType}`SeqLeft.seqLeft` has type {anchorTerm seqLeftType}`f α → (Unit → f β) → f α`, which is identical to that of {anchorName SeqRight}`seqRight` except for the fact that it returns {anchorTerm SeqLeft}`f α`.
{anchorTerm seqLeftSugar}`E1 <* E2` can be understood as a program that first executes {anchorName seqLeftSugar}`E1`, and then {anchorName seqLeftSugar}`E2`, returning the original result for {anchorName seqLeftSugar}`E1`.
If {anchorName SeqLeft}`f` has a {anchorName Monad}`Monad` instance, then {anchorTerm seqLeftSugar}`E1 <* E2` is equivalent to {lit}`do let x ← E1; _ ← E2; pure x`.
Generally speaking, {anchorName SeqLeft}`seqLeft` is useful for specifying extra conditions on a value in a validation or parser-like workflow without changing the value itself.
The definition of {anchorName Applicative}`Applicative` extends all these classes, along with {anchorName Applicative}`Functor`:
```anchor Applicative
class Applicative (f : Type u → Type v)
extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where
map := fun x y => Seq.seq (pure x) fun _ => y
seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b
seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b
```
A complete definition of {anchorName Applicative}`Applicative` requires only definitions for {anchorName Applicative}`pure` and {anchorName Seq}`seq`.
This is because there are default definitions for all of the methods from {anchorName Applicative}`Functor`, {anchorName SeqLeft}`SeqLeft`, and {anchorName SeqRight}`SeqRight`.
The {anchorName HonestFunctor}`mapConst` method of {anchorName HonestFunctor}`Functor` has its own default implementation in terms of {anchorName Applicative}`Functor.map`.
These default implementations should only be overridden with new functions that are behaviorally equivalent, but more efficient.
The default implementations should be seen as specifications for correctness as well as automatically-created code.
The default implementation for {anchorName SeqLeft}`seqLeft` is very compact.
Replacing some of the names with their syntactic sugar or their definitions can provide another view on it, so:
```anchorTerm unfoldMapConstSeqLeft
Seq.seq (Functor.map (Function.const _) a) b
```
becomes
```anchorTerm unfoldMapConstSeqLeft
fun a b => Seq.seq ((fun x _ => x) <$> a) b
```
How should {anchorTerm unfoldMapConstSeqLeft}`(fun x _ => x) <$> a` be understood?
Here, {anchorName unfoldMapConstSeqLeft}`a` has type {anchorTerm unfoldMapConstSeqLeft}`f α`, and {anchorName unfoldMapConstSeqLeft}`f` is a functor.
If {anchorName unfoldMapConstSeqLeft}`f` is {anchorName extras}`List`, then {anchorTerm mapConstList}`(fun x _ => x) <$> [1, 2, 3]` evaluates to {anchorTerm mapConstList}`[fun _ => 1, fun _ => 2, fun _ => 3`.
If {anchorName unfoldMapConstSeqLeft}`f` is {anchorName mapConstOption}`Option`, then {anchorTerm mapConstOption}`(fun x _ => x) <$> some "hello"` evaluates to {anchorTerm mapConstOption}`some (fun _ => "hello")`.
In each case, the values in the functor are replaced by functions that return the original value, ignoring their argument.
When combined with {anchorName Seq}`seq`, this function discards the values from {anchorName Seq}`seq`'s second argument.
The default implementation for {anchorName SeqRight}`seqRight` is very similar, except {anchorName FunctionConstType}`Function.const` has an additional argument {anchorName Applicative}`id`.
This definition can be understood similarly, by first introducing some standard syntactic sugar and then replacing some names with their definitions:
```anchorEvalSteps unfoldMapConstSeqRight
fun a b => Seq.seq (Functor.map (Function.const _ id) a) b
===>
fun a b => Seq.seq ((fun _ => id) <$> a) b
===>
fun a b => Seq.seq ((fun _ => fun x => x) <$> a) b
===>
fun a b => Seq.seq ((fun _ x => x) <$> a) b
```
How should {anchorTerm unfoldMapConstSeqRight}`(fun _ x => x) <$> a` be understood?
Once again, examples are useful.
{anchorTerm mapConstIdList}`fun _ x => x) <$> [1, 2, 3]` is equivalent to {anchorTerm mapConstIdList}`[fun x => x, fun x => x, fun x => x]`, and {anchorTerm mapConstIdOption}`(fun _ x => x) <$> some "hello"` is equivalent to {anchorTerm mapConstIdOption}`some (fun x => x)`.
In other words, {anchorTerm unfoldMapConstSeqRight}`(fun _ x => x) <$> a` preserves the overall shape of {anchorName unfoldMapConstSeqRight}`a`, but each value is replaced by the identity function.
From the perspective of effects, the side effects of {anchorName unfoldMapConstSeqRight}`a` occur, but the values are thrown out when it is used with {anchorName Seq}`seq`.
# Monad
%%%
tag := "complete-monad-definition"
%%%
Just as the constituent operations of {anchorName Applicative}`Applicative` are split into their own type classes, {anchorName Bind}`Bind` has its own class as well:
```anchor Bind
class Bind (m : Type u → Type v) where
bind : {α β : Type u} → m α → (α → m β) → m β
```
{anchorName Monad}`Monad` extends {anchorName Applicative}`Applicative` with {anchorName Bind}`Bind`:
```anchor Monad
class Monad (m : Type u → Type v) : Type (max (u+1) v)
extends Applicative m, Bind m where
map f x := bind x (Function.comp pure f)
seq f x := bind f fun y => Functor.map y (x ())
seqLeft x y := bind x fun a => bind (y ()) (fun _ => pure a)
seqRight x y := bind x fun _ => y ()
```
Tracing the collection of inherited methods and default methods from the entire hierarchy shows that a {anchorName Monad}`Monad` instance requires only implementations of {anchorName Bind}`bind` and {anchorName Pure}`pure`.
In other words, {anchorName Monad}`Monad` instances automatically yield implementations of {anchorName Seq}`seq`, {anchorName SeqLeft}`seqLeft`, {anchorName SeqRight}`seqRight`, {anchorName HonestFunctor}`map`, and {anchorName HonestFunctor}`mapConst`.
From the perspective of API boundaries, any type with a {anchorName Monad}`Monad` instance gets instances for {anchorName Bind}`Bind`, {anchorName Pure}`Pure`, {anchorName Seq}`Seq`, {anchorName Applicative}`Functor`, {anchorName SeqLeft}`SeqLeft`, and {anchorName SeqRight}`SeqRight`.
# Exercises
%%%
tag := "complete-functor-applicative-monad-exercises"
%%%
1. Understand the default implementations of {anchorName HonestFunctor}`map`, {anchorName Seq}`seq`, {anchorName SeqLeft}`seqLeft`, and {anchorName SeqRight}`seqRight` in {anchorName Monad}`Monad` by working through examples such as {anchorName mapConstOption}`Option` and {anchorName ApplicativeExcept (module:=Examples.FunctorApplicativeMonad)}`Except`. In other words, substitute their definitions for {anchorName Bind}`bind` and {anchorName Pure}`pure` into the default definitions, and simplify them to recover the versions {anchorName HonestFunctor}`map`, {anchorName Seq}`seq`, {anchorName SeqLeft}`seqLeft`, and {anchorName SeqRight}`seqRight` that would be written by hand.
2. On paper or in a text file, prove to yourself that the default implementations of {anchorName HonestFunctor}`map` and {anchorName Seq}`seq` satisfy the contracts for {anchorName Applicative}`Functor` and {anchorName Applicative}`Applicative`. In this argument, you're allowed to use the rules from the {anchorName Monad}`Monad` contract as well as ordinary expression evaluation. |
fp-lean/book/FPLean/FunctorApplicativeMonad/ApplicativeContract.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.FunctorApplicativeMonad"
#doc (Manual) "The Applicative Contract" =>
%%%
tag := "applicative-laws"
%%%
Just like {anchorName ApplicativeLaws}`Functor`, {anchorName ApplicativeLaws}`Monad`, and types that implement {anchorName SizedCreature}`BEq` and {anchorName MonstrousAssistantMore}`Hashable`, {anchorName ApplicativeLaws}`Applicative` has a set of rules that all instances should adhere to.
There are four rules that an applicative functor should follow:
1. It should respect identity, so {anchorTerm ApplicativeLaws}`pure id <*> v = v`
2. It should respect function composition, so {anchorTerm ApplicativeLaws}`pure (· ∘ ·) <*> u <*> v <*> w = u <*> (v <*> w)`
3. Sequencing pure operations should be a no-op, so {anchorTerm ApplicativeLaws}`pure f <*> pure x`{lit}` = `{anchorTerm ApplicativeLaws}`pure (f x)`
4. The ordering of pure operations doesn't matter, so {anchorTerm ApplicativeLaws}`u <*> pure x = pure (fun f => f x) <*> u`
To check these for the {anchorTerm ApplicativeOption}`Applicative Option` instance, start by expanding {anchorName ApplicativeLaws}`pure` into {anchorName ApplicativeOption}`some`.
The first rule states that {anchorTerm ApplicativeOptionLaws1}`some id <*> v = v`.
The definition of {anchorName fakeSeq}`seq` for {anchorName ApplicativeOption}`Option` states that this is the same as {anchorTerm ApplicativeOptionLaws1}`id <$> v = v`, which is one of the {anchorName ApplicativeLaws}`Functor` rules that have already been checked.
The second rule states that {anchorTerm ApplicativeOptionLaws2}`some (· ∘ ·) <*> u <*> v <*> w = u <*> (v <*> w)`.
If any of {anchorName ApplicativeOptionLaws2}`u`, {anchorName ApplicativeOptionLaws2}`v`, or {anchorName ApplicativeOptionLaws2}`w` is {anchorName ApplicativeOption}`none`, then both sides are {anchorName ApplicativeOption}`none`, so the property holds.
Assuming that {anchorName ApplicativeOptionLaws2}`u` is {anchorTerm OptionHomomorphism1}`some f`, that {anchorName ApplicativeOptionLaws2}`v` is {anchorTerm OptionHomomorphism1}`some g`, and that {anchorName ApplicativeOptionLaws2}`w` is {anchorTerm OptionHomomorphism1}`some x`, then this is equivalent to saying that {anchorTerm OptionHomomorphism}`some (· ∘ ·) <*> some f <*> some g <*> some x = some f <*> (some g <*> some x)`.
Evaluating the two sides yields the same result:
```anchorEvalSteps OptionHomomorphism1
some (· ∘ ·) <*> some f <*> some g <*> some x
===>
some (f ∘ ·) <*> some g <*> some x
===>
some (f ∘ g) <*> some x
===>
some ((f ∘ g) x)
===>
some (f (g x))
```
```anchorEvalSteps OptionHomomorphism2
some f <*> (some g <*> some x)
===>
some f <*> (some (g x))
===>
some (f (g x))
```
The third rule follows directly from the definition of {anchorName fakeSeq}`seq`:
```anchorEvalSteps OptionPureSeq
some f <*> some x
===>
f <$> some x
===>
some (f x)
```
In the fourth case, assume that {anchorName ApplicativeLaws}`u` is {anchorTerm OptionPureSeq}`some f`, because if it's {anchorName AlternativeOption}`none`, both sides of the equation are {anchorName AlternativeOption}`none`.
{anchorTerm OptionPureSeq}`some f <*> some x` evaluates directly to {anchorTerm OptionPureSeq}`some (f x)`, as does {anchorTerm OptionPureSeq2}`some (fun g => g x) <*> some f`.
# All Applicatives are Functors
%%%
tag := "applicatives-are-functors"
%%%
The two operators for {anchorName ApplicativeMap}`Applicative` are enough to define {anchorName ApplicativeMap}`map`:
```anchor ApplicativeMap
def map [Applicative f] (g : α → β) (x : f α) : f β :=
pure g <*> x
```
This can only be used to implement {anchorName ApplicativeLaws}`Functor` if the contract for {anchorName ApplicativeLaws}`Applicative` guarantees the contract for {anchorName ApplicativeLaws}`Functor`, however.
The first rule of {anchorName ApplicativeLaws}`Functor` is that {anchorTerm AppToFunTerms}`id <$> x = x`, which follows directly from the first rule for {anchorName ApplicativeLaws}`Applicative`.
The second rule of {anchorName ApplicativeLaws}`Functor` is that {anchorTerm AppToFunTerms}`map (f ∘ g) x = map f (map g x)`.
Unfolding the definition of {anchorName AppToFunTerms}`map` here results in {anchorTerm AppToFunTerms}`pure (f ∘ g) <*> x = pure f <*> (pure g <*> x)`.
Using the rule that sequencing pure operations is a no-op, the left side can be rewritten to {anchorTerm AppToFunTerms}`pure (· ∘ ·) <*> pure f <*> pure g <*> x`.
This is an instance of the rule that states that applicative functors respect function composition.
This justifies a definition of {anchorName ApplicativeMap}`Applicative` that extends {anchorName ApplicativeLaws}`Functor`, with a default definition of {anchorTerm ApplicativeExtendsFunctorOne}`map` given in terms of {anchorName ApplicativeExtendsFunctorOne}`pure` and {anchorName ApplicativeExtendsFunctorOne}`seq`:
```anchor ApplicativeExtendsFunctorOne
class Applicative (f : Type → Type) extends Functor f where
pure : α → f α
seq : f (α → β) → (Unit → f α) → f β
map g x := seq (pure g) (fun () => x)
```
# All Monads are Applicative Functors
%%%
tag :="monads-are-applicative"
%%%
An instance of {anchorName MonadExtends}`Monad` already requires an implementation of {anchorName MonadSeq}`pure`.
Together with {anchorName MonadExtends}`bind`, this is enough to define {anchorName MonadSeq}`seq`:
```anchor MonadSeq
def seq [Monad m] (f : m (α → β)) (x : Unit → m α) : m β := do
let g ← f
let y ← x ()
pure (g y)
```
Once again, checking that the {anchorName MonadSeq}`Monad` contract implies the {anchorName MonadExtends}`Applicative` contract will allow this to be used as a default definition for {anchorTerm MonadExtends}`seq` if {anchorName MonadSeq}`Monad` extends {anchorName MonadExtends}`Applicative`.
The rest of this section consists of an argument that this implementation of {anchorTerm MonadExtends}`seq` based on {anchorName MonadExtends}`bind` in fact satisfies the {anchorName MonadExtends}`Applicative` contract.
One of the beautiful things about functional programming is that this kind of argument can be worked out on a piece of paper with a pencil, using the kinds of evaluation rules from {ref "evaluating"}[the initial section on evaluating expressions].
Thinking about the meanings of the operations while reading these arguments can sometimes help with understanding.
Replacing {kw}`do`-notation with explicit uses of {lit}`>>=` makes it easier to apply the {anchorName MonadSeqDesugar}`Monad` rules:
```anchor MonadSeqDesugar
def seq [Monad m] (f : m (α → β)) (x : Unit → m α) : m β := do
f >>= fun g =>
x () >>= fun y =>
pure (g y)
```
To check that this definition respects identity, check that {anchorTerm mSeqRespIdInit}`seq (pure id) (fun () => v) = v`.
The left hand side is equivalent to {anchorTerm mSeqRespIdInit}`pure id >>= fun g => (fun () => v) () >>= fun y => pure (g y)`.
The unit function in the middle can be eliminated immediately, yielding {anchorTerm mSeqRespIdInit}`pure id >>= fun g => v >>= fun y => pure (g y)`.
Using the fact that {anchorName mSeqRespIdInit}`pure` is a left identity of {anchorTerm mSeqRespIdInit}`>>=`, this is the same as {anchorTerm mSeqRespIdInit}`v >>= fun y => pure (id y)`, which is {anchorTerm mSeqRespIdInit}`v >>= fun y => pure y`.
Because {anchorTerm mSeqRespIdInit}`fun x => f x` is the same as {anchorName mSeqRespIdInit}`f`, this is the same as {anchorTerm mSeqRespIdInit}`v >>= pure`, and the fact that {anchorName mSeqRespIdInit}`pure` is a right identity of {anchorTerm mSeqRespIdInit}`>>=` can be used to get {anchorName mSeqRespIdInit}`v`.
This kind of informal reasoning can be made easier to read with a bit of reformatting.
In the following chart, read “{lit}`EXPR1 ={ REASON }= EXPR2`” as “{lit}`EXPR1` is the same as {lit}`EXPR2` because {lit}`REASON`”:
```anchorEqSteps mSeqRespId
pure id >>= fun g => v >>= fun y => pure (g y)
={
/-- `pure` is a left identity of `>>=` -/
by simp [LawfulMonad.pure_bind]
}=
v >>= fun y => pure (id y)
={
/-- Reduce the call to `id` -/
}=
v >>= fun y => pure y
={
/-- `fun x => f x` is the same as `f` -/
by
have {α β } {f : α → β} : (fun x => f x) = (f) := rfl
rfl
}=
v >>= pure
={
/-- `pure` is a right identity of `>>=` -/
by simp
}=
v
```
To check that it respects function composition, check that {anchorTerm ApplicativeLaws}`pure (· ∘ ·) <*> u <*> v <*> w = u <*> (v <*> w)`.
The first step is to replace {lit}`<*>` with this definition of {anchorName MonadSeqDesugar}`seq`.
After that, a (somewhat long) series of steps that use the identity and associativity rules from the {anchorName ApplicativeLaws}`Monad` contract is enough to get from one to the other:
```anchorEqSteps mSeqRespComp
seq (seq (seq (pure (· ∘ ·)) (fun _ => u))
(fun _ => v))
(fun _ => w)
={
/-- Definition of `seq` -/
}=
((pure (· ∘ ·) >>= fun f =>
u >>= fun x =>
pure (f x)) >>= fun g =>
v >>= fun y =>
pure (g y)) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- `pure` is a left identity of `>>=` -/
by simp only [LawfulMonad.pure_bind]
}=
((u >>= fun x =>
pure (x ∘ ·)) >>= fun g =>
v >>= fun y =>
pure (g y)) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- Insertion of parentheses for clarity -/
}=
((u >>= fun x =>
pure (x ∘ ·)) >>= (fun g =>
v >>= fun y =>
pure (g y))) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- Associativity of `>>=` -/
by simp only [LawfulMonad.bind_assoc]
}=
(u >>= fun x =>
pure (x ∘ ·) >>= fun g =>
v >>= fun y => pure (g y)) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- `pure` is a left identity of `>>=` -/
by simp only [LawfulMonad.pure_bind]
}=
(u >>= fun x =>
v >>= fun y =>
pure (x ∘ y)) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- Associativity of `>>=` -/
by simp only [LawfulMonad.bind_assoc]
}=
u >>= fun x =>
v >>= fun y =>
pure (x ∘ y) >>= fun h =>
w >>= fun z =>
pure (h z)
={
/-- `pure` is a left identity of `>>=` -/
by simp [bind_pure_comp]; rfl
}=
u >>= fun x =>
v >>= fun y =>
w >>= fun z =>
pure ((x ∘ y) z)
={
/-- Definition of function composition -/
}=
u >>= fun x =>
v >>= fun y =>
w >>= fun z =>
pure (x (y z))
={
/--
Time to start moving backwards!
`pure` is a left identity of `>>=`
-/
by simp
}=
u >>= fun x =>
v >>= fun y =>
w >>= fun z =>
pure (y z) >>= fun q =>
pure (x q)
={
/-- Associativity of `>>=` -/
by simp
}=
u >>= fun x =>
v >>= fun y =>
(w >>= fun p =>
pure (y p)) >>= fun q =>
pure (x q)
={
/-- Associativity of `>>=` -/
by simp
}=
u >>= fun x =>
(v >>= fun y =>
w >>= fun q =>
pure (y q)) >>= fun z =>
pure (x z)
={
/-- This includes the definition of `seq` -/
}=
u >>= fun x =>
seq v (fun () => w) >>= fun q =>
pure (x q)
={
/-- This also includes the definition of `seq` -/
}=
seq u (fun () => seq v (fun () => w))
```
To check that sequencing pure operations is a no-op:
```anchorEqSteps mSeqPureNoOp
seq (pure f) (fun () => pure x)
={
/-- Replacing `seq` with its definition -/
}=
pure f >>= fun g =>
pure x >>= fun y =>
pure (g y)
={
/-- `pure` is a left identity of `>>=` -/
by simp
}=
pure f >>= fun g =>
pure (g x)
={
/-- `pure` is a left identity of `>>=` -/
by simp
}=
pure (f x)
```
And finally, to check that the ordering of pure operations doesn't matter:
```anchorEqSteps mSeqPureNoOrder
seq u (fun () => pure x)
={
/-- Definition of `seq` -/
}=
u >>= fun f =>
pure x >>= fun y =>
pure (f y)
={
/-- `pure` is a left identity of `>>=` -/
by simp
}=
u >>= fun f =>
pure (f x)
={
/-- Clever replacement of one expression by an equivalent one that makes the rule match -/
}=
u >>= fun f =>
pure ((fun g => g x) f)
={
/-- `pure` is a left identity of `>>=` -/
by simp [LawfulMonad.pure_bind]
}=
pure (fun g => g x) >>= fun h =>
u >>= fun f =>
pure (h f)
={
/-- Definition of `seq` -/
}=
seq (pure (fun f => f x)) (fun () => u)
```
This justifies a definition of {anchorName ApplicativeLaws}`Monad` that extends {anchorName ApplicativeLaws}`Applicative`, with a default definition of {anchorTerm MonadExtends}`seq`:
```anchor MonadExtends
class Monad (m : Type → Type) extends Applicative m where
bind : m α → (α → m β) → m β
seq f x :=
bind f fun g =>
bind (x ()) fun y =>
pure (g y)
```
{anchorName MonadExtends}`Applicative`'s own default definition of {anchorTerm ApplicativeExtendsFunctorOne}`map` means that every {anchorName MonadExtends}`Monad` instance automatically generates {anchorName MonadExtends}`Applicative` and {anchorName ApplicativeExtendsFunctorOne}`Functor` instances as well.
# Additional Stipulations
%%%
tag := "additional-stipulations"
%%%
In addition to adhering to the individual contracts associated with each type class, combined implementations {anchorName ApplicativeLaws}`Functor`, {anchorName ApplicativeLaws}`Applicative` and {anchorName ApplicativeLaws}`Monad` should work equivalently to these default implementations.
In other words, a type that provides both {anchorName ApplicativeLaws}`Applicative` and {anchorName ApplicativeLaws}`Monad` instances should not have an implementation of {anchorTerm MonadExtends}`seq` that works differently from the version that the {anchorName MonadSeq}`Monad` instance generates as a default implementation.
This is important because polymorphic functions may be refactored to replace a use of {lit}`>>=` with an equivalent use of {lit}`<*>`, or a use of {lit}`<*>` with an equivalent use of {lit}`>>=`.
This refactoring should not change the meaning of programs that use this code.
This rule explains why {anchorName ValidateAndThen}`Validate.andThen` should not be used to implement {anchorName MonadExtends}`bind` in a {anchorName ApplicativeLaws}`Monad` instance.
On its own, it obeys the monad contract.
However, when it is used to implement {anchorTerm MonadExtends}`seq`, the behavior is not equivalent to {anchorTerm MonadExtends}`seq` itself.
To see where they differ, take the example of two computations, both of which return errors.
Start with an example of a case where two errors should be returned, one from validating a function (which could have just as well resulted from a prior argument to the function), and one from validating an argument:
```anchor counterexample
def notFun : Validate String (Nat → String) :=
.errors { head := "First error", tail := [] }
def notArg : Validate String Nat :=
.errors { head := "Second error", tail := [] }
```
Combining them with the version of {lit}`<*>` from {anchorName Validate}`Validate`'s {anchorName ApplicativeValidate}`Applicative` instance results in both errors being reported to the user:
```anchorEvalSteps realSeq
notFun <*> notArg
===>
match notFun with
| .ok g => g <$> notArg
| .errors errs =>
match notArg with
| .ok _ => .errors errs
| .errors errs' => .errors (errs ++ errs')
===>
match notArg with
| .ok _ =>
.errors { head := "First error", tail := [] }
| .errors errs' =>
.errors ({ head := "First error", tail := [] } ++ errs')
===>
.errors
({ head := "First error", tail := [] } ++
{ head := "Second error", tail := []})
===>
.errors {
head := "First error",
tail := ["Second error"]
}
```
Using the version of {anchorName MonadSeqDesugar}`seq` that was implemented with {lit}`>>=`, here rewritten to {anchorName fakeSeq}`andThen`, results in only the first error being available:
```anchorEvalSteps fakeSeq
seq notFun (fun () => notArg)
===>
notFun.andThen fun g =>
notArg.andThen fun y =>
pure (g y)
===>
match notFun with
| .errors errs => .errors errs
| .ok val =>
(fun g =>
notArg.andThen fun y =>
pure (g y)) val
===>
.errors { head := "First error", tail := [] }
``` |
fp-lean/book/FPLean/FunctorApplicativeMonad/Applicative.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.FunctorApplicativeMonad"
#doc (Manual) "Applicative Functors" =>
%%%
tag := "applicative"
%%%
An _applicative functor_ is a functor that has two additional operations available: {anchorName ApplicativeOption}`pure` and {anchorName ApplicativeOption}`seq`.
{anchorName ApplicativeOption}`pure` is the same operator used in {anchorName ApplicativeLaws}`Monad`, because {anchorName ApplicativeLaws}`Monad` in fact inherits from {anchorName ApplicativeOption}`Applicative`.
{anchorName ApplicativeOption}`seq` is much like {anchorName FunctorNames}`map`: it allows a function to be used in order to transform the contents of a datatype.
However, with {anchorName ApplicativeOption}`seq`, the function is itself contained in the datatype: {anchorTerm seqType}`f (α → β) → (Unit → f α) → f β`.
Having the function under the type {anchorName seqType}`f` allows the {anchorName ApplicativeOption}`Applicative` instance to control how the function is applied, while {anchorName FunctorNames}`Functor.map` unconditionally applies a function.
The second argument has a type that begins with {anchorTerm seqType}`Unit →` to allow the definition of {anchorName ApplicativeOption}`seq` to short-circuit in cases where the function will never be applied.
The value of this short-circuiting behavior can be seen in the instance of {anchorTerm ApplicativeOption}`Applicative Option`:
```anchor ApplicativeOption
instance : Applicative Option where
pure x := .some x
seq f x :=
match f with
| none => none
| some g => g <$> x ()
```
In this case, if there is no function for {anchorName ApplicativeOption}`seq` to apply, then there is no need to compute its argument, so {anchorName ApplicativeOption}`x` is never called.
The same consideration informs the instance of {anchorName ApplicativeExcept}`Applicative` for {anchorName ApplicativeExcept}`Except`:
```anchor ApplicativeExcept
instance : Applicative (Except ε) where
pure x := .ok x
seq f x :=
match f with
| .error e => .error e
| .ok g => g <$> x ()
```
This short-circuiting behavior depends only on the {anchorName AlternativeOption}`Option` or {anchorName ApplicativeExcept}`Except` structures that _surround_ the function, rather than on the function itself.
Monads can be seen as a way of capturing the notion of sequentially executing statements into a pure functional language.
The result of one statement can affect which further statements run.
This can be seen in the type of {anchorName bindType}`bind`: {anchorTerm bindType}`m α → (α → m β) → m β`.
The first statement's resulting value is an input into a function that computes the next statement to execute.
Successive uses of {anchorName bindType}`bind` are like a sequence of statements in an imperative programming language, and {anchorName bindType}`bind` is powerful enough to implement control structures like conditionals and loops.
Following this analogy, {anchorName ApplicativeId}`Applicative` captures function application in a language that has side effects.
The arguments to a function in languages like Kotlin or C# are evaluated from left to right.
Side effects performed by earlier arguments occur before those performed by later arguments.
A function is not powerful enough to implement custom short-circuiting operators that depend on the specific _value_ of an argument, however.
Typically, {anchorName ApplicativeExtendsFunctorOne}`seq` is not invoked directly.
Instead, the operator {lit}`<*>` is used.
This operator wraps its second argument in {lit}`fun () => ...`, simplifying the call site.
In other words, {anchorTerm seqSugar}`E1 <*> E2` is syntactic sugar for {anchorTerm seqSugar}`Seq.seq E1 (fun () => E2)`.
The key feature that allows {anchorName ApplicativeExtendsFunctorOne}`seq` to be used with multiple arguments is that a multiple-argument Lean function is really a single-argument function that returns another function that's waiting for the rest of the arguments.
In other words, if the first argument to {anchorName ApplicativeExtendsFunctorOne}`seq` is awaiting multiple arguments, then the result of the {anchorName ApplicativeExtendsFunctorOne}`seq` will be awaiting the rest.
For example, {anchorTerm somePlus}`some Plus.plus` can have the type {anchorTerm somePlus}`Option (Nat → Nat → Nat)`.
Providing one argument, {anchorTerm somePlusFour}`some Plus.plus <*> some 4`, results in the type {anchorTerm somePlusFour}`Option (Nat → Nat)`.
This can itself be used with {anchorName ApplicativeExtendsFunctorOne}`seq`, so {anchorTerm somePlusFourSeven}`some Plus.plus <*> some 4 <*> some 7` has the type {anchorTerm somePlusFourSeven}`Option Nat`.
Not every functor is applicative.
{anchorName Pair}`Pair` is like the built-in product type {anchorName names}`Prod`:
```anchor Pair
structure Pair (α β : Type) : Type where
first : α
second : β
```
Like {anchorName ApplicativeExcept}`Except`, {anchorTerm PairType}`Pair` has type {anchorTerm PairType}`Type → Type → Type`.
This means that {anchorTerm FunctorPair}`Pair α` has type {anchorTerm PairType}`Type → Type`, and a {anchorName FunctorPair}`Functor` instance is possible:
```anchor FunctorPair
instance : Functor (Pair α) where
map f x := ⟨x.first, f x.second⟩
```
This instance obeys the {anchorName FunctorPair}`Functor` contract.
The two properties to check are that {anchorEvalStep checkPairMapId 0}`id <$> Pair.mk x y`{lit}` = `{anchorEvalStep checkPairMapId 2}`Pair.mk x y` and that {anchorEvalStep checkPairMapComp1 0}`f <$> g <$> Pair.mk x y`{lit}` = `{anchorEvalStep checkPairMapComp2 0}`(f ∘ g) <$> Pair.mk x y`.
The first property can be checked by just stepping through the evaluation of the left side, and noticing that it evaluates to the right side:
```anchorEvalSteps checkPairMapId
id <$> Pair.mk x y
===>
Pair.mk x (id y)
===>
Pair.mk x y
```
The second can be checked by stepping through both sides, and noting that they yield the same result:
```anchorEvalSteps checkPairMapComp1
f <$> g <$> Pair.mk x y
===>
f <$> Pair.mk x (g y)
===>
Pair.mk x (f (g y))
```
```anchorEvalSteps checkPairMapComp2
(f ∘ g) <$> Pair.mk x y
===>
Pair.mk x ((f ∘ g) y)
===>
Pair.mk x (f (g y))
```
Attempting to define an {anchorName ApplicativeExcept}`Applicative` instance, however, does not work so well.
It will require a definition of {anchorName Pairpure (show := pure)}`Pair.pure`:
```anchor Pairpure
def Pair.pure (x : β) : Pair α β := _
```
```anchorError Pairpure
don't know how to synthesize placeholder
context:
β α : Type
x : β
⊢ Pair α β
```
There is a value with type {anchorName Pairpure2}`β` in scope (namely {anchorName Pairpure2}`x`), and the error message from the underscore suggests that the next step is to use the constructor {anchorName Pairpure2}`Pair.mk`:
```anchor Pairpure2
def Pair.pure (x : β) : Pair α β := Pair.mk _ x
```
```anchorError Pairpure2
don't know how to synthesize placeholder for argument `first`
context:
β α : Type
x : β
⊢ α
```
Unfortunately, there is no {anchorName Pairpure2}`α` available.
Because {anchorName Pairpure2 (show := pure)}`Pair.pure` would need to work for _all possible types_ {anchorName Pairpure2}`α` to define an instance of {anchorTerm ApplicativePair}`Applicative (Pair α)`, this is impossible.
After all, a caller could choose {anchorName Pairpure2}`α` to be {anchorName ApplicativePair}`Empty`, which has no values at all.
# A Non-Monadic Applicative
%%%
tag := "validate"
%%%
When validating user input to a form, it's generally considered to be best to provide many errors at once, rather than one error at a time.
This allows the user to have an overview of what is needed to please the computer, rather than feeling badgered as they correct the errors field by field.
Ideally, validating user input will be visible in the type of the function that's doing the validating.
It should return a datatype that is specific—checking that a text box contains a number should return an actual numeric type, for instance.
A validation routine could throw an exception when the input does not pass validation.
Exceptions have a major drawback, however: they terminate the program at the first error, making it impossible to accumulate a list of errors.
On the other hand, the common design pattern of accumulating a list of errors and then failing when it is non-empty is also problematic.
A long nested sequences of {kw}`if` statements that validate each sub-section of the input data is hard to maintain, and it's easy to lose track of an error message or two.
Ideally, validation can be performed using an API that enables a new value to be returned yet automatically tracks and accumulates error messages.
An applicative functor called {anchorName Validate}`Validate` provides one way to implement this style of API.
Like the {anchorName ApplicativeExcept}`Except` monad, {anchorName Validate}`Validate` allows a new value to be constructed that characterizes the validated data accurately.
Unlike {anchorName ApplicativeExcept}`Except`, it allows multiple errors to be accumulated, without a risk of forgetting to check whether the list is empty.
## User Input
%%%
tag := "user-input"
%%%
As an example of user input, take the following structure:
```anchor RawInput
structure RawInput where
name : String
birthYear : String
```
The business logic to be implemented is the following:
1. The name may not be empty
2. The birth year must be numeric and non-negative
3. The birth year must be greater than 1900, and less than or equal to the year in which the form is validated
Representing these as a datatype will require a new feature, called _subtypes_.
With this tool in hand, a validation framework can be written that uses an applicative functor to track errors, and these rules can be implemented in the framework.
## Subtypes
%%%
tag := "subtypes"
%%%
Representing these conditions is easiest with one additional Lean type, called {anchorName Subtype}`Subtype`:
```anchor Subtype
structure Subtype {α : Type} (p : α → Prop) where
val : α
property : p val
```
This structure has two type parameters: an implicit parameter that is the type of data {anchorName Subtype}`α`, and an explicit parameter {anchorName Subtype}`p` that is a predicate over {anchorName Subtype}`α`.
A _predicate_ is a logical statement with a variable in it that can be replaced with a value to yield an actual statement, like the {ref "overloading-indexing"}[parameter to {moduleName}`GetElem`] that describes what it means for an index to be in bounds for a lookup.
In the case of {anchorName Subtype}`Subtype`, the predicate slices out some subset of the values of {anchorName Subtype}`α` for which the predicate holds.
The structure's two fields are, respectively, a value from {anchorName Subtype}`α` and evidence that the value satisfies the predicate {anchorName Subtype}`p`.
Lean has special syntax for {anchorName Subtype}`Subtype`.
If {anchorName Subtype}`p` has type {anchorTerm Subtype}`α → Prop`, then the type {anchorTerm subtypeSugarIn}`Subtype p` can also be written {anchorTerm subtypeSugar}`{x : α // p x}`, or even {anchorTerm subtypeSugar2}`{x // p x}` when the type {anchorName Subtype}`α` can be inferred automatically.
{ref "positive-numbers"}[Representing positive numbers as inductive types] is clear and easy to program with.
However, it has a key disadvantage.
While {anchorName names}`Nat` and {anchorName names}`Int` have the structure of ordinary inductive types from the perspective of Lean programs, the compiler treats them specially and uses fast arbitrary-precision number libraries to implement them.
This is not the case for additional user-defined types.
However, a subtype of {anchorName names}`Nat` that restricts it to non-zero numbers allows the new type to use the efficient representation while still ruling out zero at compile time:
```anchor FastPos
def FastPos : Type := {x : Nat // x > 0}
```
The smallest fast positive number is still one.
Now, instead of being a constructor of an inductive type, it's an instance of a structure that's constructed with angle brackets.
The first argument is the underlying {anchorName FastPos}`Nat`, and the second argument is the evidence that said {anchorName FastPos}`Nat` is greater than zero:
```anchor one
def one : FastPos := ⟨1, by decide⟩
```
The proposition {anchorTerm onep}`1 > 0` is decidable, so the {tactic}`decide` tactic produces the necessary evidence.
The {anchorName OfNatFastPos}`OfNat` instance is very much like that for {anchorName Pos (module:=Examples.Classes)}`Pos`, except it uses a short tactic proof to provide evidence that {lit}`n + 1 > 0`:
```anchor OfNatFastPos
instance : OfNat FastPos (n + 1) where
ofNat := ⟨n + 1, by simp⟩
```
Here, {tactic}`simp` is needed because {tactic}`decide` requires concrete values, but the proposition in question is {anchorTerm OfNatFastPosp}`n + 1 > 0`.
Subtypes are a two-edged sword.
They allow efficient representation of validation rules, but they transfer the burden of maintaining these rules to the users of the library, who have to _prove_ that they are not violating important invariants.
Generally, it's a good idea to use them internally to a library, providing an API to users that automatically ensures that all invariants are satisfied, with any necessary proofs being internal to the library.
Checking whether a value of type {anchorName NatFastPosRemarks}`α` is in the subtype {anchorTerm NatFastPosRemarks}`{x : α // p x}` usually requires that the proposition {anchorTerm NatFastPosRemarks}`p x` be decidable.
The {ref "equality-and-ordering"}[section on equality and ordering classes] describes how decidable propositions can be used with {kw}`if`.
When {kw}`if` is used with a decidable proposition, a name can be provided.
In the {kw}`then` branch, the name is bound to evidence that the proposition is true, and in the {kw}`else` branch, it is bound to evidence that the proposition is false.
This comes in handy when checking whether a given {anchorName NatFastPos}`Nat` is positive:
```anchor NatFastPos
def Nat.asFastPos? (n : Nat) : Option FastPos :=
if h : n > 0 then
some ⟨n, h⟩
else none
```
In the {kw}`then` branch, {anchorName NatFastPos}`h` is bound to evidence that {anchorTerm NatFastPos}`n > 0`, and this evidence can be used as the second argument to {anchorName Subtype}`Subtype`'s constructor.
## Validated Input
%%%
tag := "validated-input"
%%%
The validated user input is a structure that expresses the business logic using multiple techniques:
* The structure type itself encodes the year in which it was checked for validity, so that {anchorTerm CheckedInputEx}`CheckedInput 2019` is not the same type as {anchorTerm CheckedInputEx}`CheckedInput 2020`
* The birth year is represented as a {anchorName CheckedInput}`Nat` rather than a {anchorName CheckedInput}`String`
* Subtypes are used to constrain the allowed values in the name and birth year fields
```anchor CheckedInput
structure CheckedInput (thisYear : Nat) : Type where
name : {n : String // n ≠ ""}
birthYear : {y : Nat // y > 1900 ∧ y ≤ thisYear}
```
:::paragraph
An input validator should take the current year and a {anchorName RawInput}`RawInput` as arguments, returning either a checked input or at least one validation failure.
This is represented by the {anchorName Validate}`Validate` type:
```anchor Validate
inductive Validate (ε α : Type) : Type where
| ok : α → Validate ε α
| errors : NonEmptyList ε → Validate ε α
```
It looks very much like {anchorName ApplicativeExcept}`Except`.
The only difference is that the {anchorName Validate}`errors` constructor may contain more than one failure.
:::
{anchorName Validate}`Validate` is a functor.
Mapping a function over it transforms any successful value that might be present, just as in the {anchorName FunctorValidate}`Functor` instance for {anchorName ApplicativeExcept}`Except`:
```anchor FunctorValidate
instance : Functor (Validate ε) where
map f
| .ok x => .ok (f x)
| .errors errs => .errors errs
```
The {anchorName ApplicativeValidate}`Applicative` instance for {anchorName ApplicativeValidate}`Validate` has an important difference from the instance for {anchorName ApplicativeExcept}`Except`: while the instance for {anchorName ApplicativeExcept}`Except` terminates at the first error encountered, the instance for {anchorName ApplicativeValidate}`Validate` is careful to accumulate all errors from _both_ the function and the argument branches:
```anchor ApplicativeValidate
instance : Applicative (Validate ε) where
pure := .ok
seq f x :=
match f with
| .ok g => g <$> (x ())
| .errors errs =>
match x () with
| .ok _ => .errors errs
| .errors errs' => .errors (errs ++ errs')
```
:::paragraph
Using {anchorName ApplicativeValidate}`.errors` together with the constructor for {anchorName Validate}`NonEmptyList` is a bit verbose.
Helpers like {anchorName reportError}`reportError` make code more readable.
In this application, error reports will consist of field names paired with messages:
```anchor Field
def Field := String
```
```anchor reportError
def reportError (f : Field) (msg : String) : Validate (Field × String) α :=
.errors { head := (f, msg), tail := [] }
```
:::
The {anchorName ApplicativeValidate}`Applicative` instance for {anchorName ApplicativeValidate}`Validate` allows the checking procedures for each field to be written independently and then composed.
Checking a name consists of ensuring that a string is non-empty, then returning evidence of this fact in the form of a {anchorName Subtype}`Subtype`.
This uses the evidence-binding version of {kw}`if`:
```anchor checkName
def checkName (name : String) :
Validate (Field × String) {n : String // n ≠ ""} :=
if h : name = "" then
reportError "name" "Required"
else pure ⟨name, h⟩
```
In the {kw}`then` branch, {anchorName checkName}`h` is bound to evidence that {anchorTerm checkName}`name = ""`, while it is bound to evidence that {lit}`¬name = ""` in the {kw}`else` branch.
It's certainly the case that some validation errors make other checks impossible.
For example, it makes no sense to check whether the birth year field is greater than 1900 if a confused user wrote the word {anchorTerm checkDavidSyzygy}`"syzygy"` instead of a number.
Checking the allowed range of the number is only meaningful after ensuring that the field in fact contains a number.
This can be expressed using the function {anchorName ValidateAndThen (show := andThen)}`Validate.andThen`:
```anchor ValidateAndThen
def Validate.andThen (val : Validate ε α)
(next : α → Validate ε β) : Validate ε β :=
match val with
| .errors errs => .errors errs
| .ok x => next x
```
While this function's type signature makes it suitable to be used as {anchorName bindType}`bind` in a {anchorTerm bindType}`Monad` instance, there are good reasons not to do so.
They are described {ref "additional-stipulations"}[in the section that describes the {anchorName ApplicativeExcept}`Applicative` contract].
To check that the birth year is a number, a built-in function called {anchorTerm CheckedInputEx}`String.toNat? : String → Option Nat` is useful.
It's most user-friendly to eliminate leading and trailing whitespace first using {anchorName CheckedInputEx}`String.trim`:
```anchor checkYearIsNat
def checkYearIsNat (year : String) : Validate (Field × String) Nat :=
match year.trim.toNat? with
| none => reportError "birth year" "Must be digits"
| some n => pure n
```
:::paragraph
To check that the provided year is in the expected range, nested uses of the evidence-providing form of {kw}`if` are in order:
```anchor checkBirthYear
def checkBirthYear (thisYear year : Nat) :
Validate (Field × String) {y : Nat // y > 1900 ∧ y ≤ thisYear} :=
if h : year > 1900 then
if h' : year ≤ thisYear then
pure ⟨year, by simp [*]⟩
else reportError "birth year" s!"Must be no later than {thisYear}"
else reportError "birth year" "Must be after 1900"
```
:::
:::paragraph
Finally, these three components can be combined using {anchorTerm checkInput}`<*>`:
```anchor checkInput
def checkInput (year : Nat) (input : RawInput) :
Validate (Field × String) (CheckedInput year) :=
pure CheckedInput.mk <*>
checkName input.name <*>
(checkYearIsNat input.birthYear).andThen fun birthYearAsNat =>
checkBirthYear year birthYearAsNat
```
:::
:::paragraph
Testing {anchorName checkDavid1984}`checkInput` shows that it can indeed return multiple pieces of feedback:
```anchor checkDavid1984
#eval checkInput 2023 {name := "David", birthYear := "1984"}
```
```anchorInfo checkDavid1984
Validate.ok { name := "David", birthYear := 1984 }
```
```anchor checkBlank2045
#eval checkInput 2023 {name := "", birthYear := "2045"}
```
```anchorInfo checkBlank2045
Validate.errors { head := ("name", "Required"), tail := [("birth year", "Must be no later than 2023")] }
```
```anchor checkDavidSyzygy
#eval checkInput 2023 {name := "David", birthYear := "syzygy"}
```
```anchorInfo checkDavidSyzygy
Validate.errors { head := ("birth year", "Must be digits"), tail := [] }
```
:::
Form validation with {anchorName checkInput}`checkInput` illustrates a key advantage of {anchorName ApplicativeNames}`Applicative` over {anchorName MonadExtends}`Monad`.
Because {lit}`>>=` provides enough power to modify the rest of the program's execution based on the value from the first step, it _must_ receive a value from the first step to pass on.
If no value is received (e.g. because an error has occurred), then {lit}`>>=` cannot execute the rest of the program.
{anchorName Validate}`Validate` demonstrates why it can be useful to run the rest of the program anyway: in cases where the earlier data isn't needed, running the rest of the program can yield useful information (in this case, more validation errors).
{anchorName ApplicativeNames}`Applicative`'s {lit}`<*>` may run both of its arguments before recombining the results.
Similarly, {lit}`>>=` forces sequential execution.
Each step must complete before the next may run.
This is generally useful, but it makes it impossible to have parallel execution of different threads that naturally emerges from the program's actual data dependencies.
A more powerful abstraction like {anchorName MonadExtends}`Monad` increases the flexibility that's available to the API consumer, but it decreases the flexibility that is available to the API implementor. |
fp-lean/book/FPLean/FunctorApplicativeMonad/Conveniences.lean | |
fp-lean/book/FPLean/FunctorApplicativeMonad/Universes.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.Universes"
#doc (Manual) "Universes" =>
%%%
tag := "universe-levels"
%%%
In the interests of simplicity, this book has thus far papered over an important feature of Lean: _universes_.
A universe is a type that classifies other types.
Two of them are familiar: {anchorTerm TypeType}`Type` and {anchorTerm PropType}`Prop`.
{anchorTerm SomeTypes}`Type` classifies ordinary types, such as {anchorName SomeTypes}`Nat`, {anchorTerm SomeTypes}`String`, {anchorTerm SomeTypes}`Int → String × Char`, and {anchorTerm SomeTypes}`IO Unit`.
{anchorTerm PropType}`Prop` classifies propositions that may be true or false, such as {anchorTerm SomeTypes}`"nisse" = "elf"` or {anchorTerm SomeTypes}`3 > 2`.
The type of {anchorTerm PropType}`Prop` is {anchorTerm SomeTypes}`Type`:
```anchor PropType
#check Prop
```
```anchorInfo PropType
Prop : Type
```
For technical reasons, more universes than these two are needed.
In particular, {anchorTerm SomeTypes}`Type` cannot itself be a {anchorTerm SomeTypes}`Type`.
This would allow a logical paradox to be constructed and undermine Lean's usefulness as a theorem prover.
The formal argument for this is known as _Girard's Paradox_.
It is related to a better-known paradox known as _Russell's Paradox_, which was used to show that early versions of set theory were inconsistent.
In these set theories, a set can be defined by a property.
For example, one might have the set of all red things, the set of all fruit, the set of all natural numbers, or even the set of all sets.
Given a set, one can ask whether a given element is contained in it.
For instance, a bluebird is not contained in the set of all red things, but the set of all red things is contained in the set of all sets.
Indeed, the set of all sets even contains itself.
What about the set of all sets that do not contain themselves?
It contains the set of all red things, as the set of all red things is not itself red.
It does not contain the set of all sets, because the set of all sets contains itself.
But does it contain itself?
If it does contain itself, then it cannot contain itself.
But if it does not, then it must.
This is a contradiction, which demonstrates that something was wrong with the initial assumptions.
In particular, allowing sets to be constructed by providing an arbitrary property is too powerful.
Later versions of set theory restrict the formation of sets to remove the paradox.
A related paradox can be constructed in versions of dependent type theory that assign the type {anchorTerm SomeTypes}`Type` to {anchorTerm SomeTypes}`Type`.
To ensure that Lean has consistent logical foundations and can be used as a tool for mathematics, {anchorTerm SomeTypes}`Type` needs to have some other type.
This type is called {anchorTerm SomeTypes}`Type 1`:
```anchor TypeType
#check Type
```
```anchorInfo TypeType
Type : Type 1
```
Similarly, {anchorTerm Type1Type}`Type 1` is a {anchorTerm Type1Type}`Type 2`,
{anchorTerm Type2Type}`Type 2` is a {anchorTerm Type2Type}`Type 3`,
{anchorTerm Type3Type}`Type 3` is a {anchorTerm Type3Type}`Type 4`, and so forth.
Function types occupy the smallest universe that can contain both the argument type and the return type.
This means that {anchorTerm NatNatType}`Nat → Nat` is a {anchorTerm NatNatType}`Type`, {anchorTerm Fun00Type}`Type → Type` is a {anchorTerm Fun00Type}`Type 1`, and {anchorTerm Fun12Type}`Type 3` is a {anchorTerm Fun12Type}`Type 1 → Type 2`.
There is one exception to this rule.
If the return type of a function is a {anchorTerm PropType}`Prop`, then the whole function type is in {anchorTerm PropType}`Prop`, even if the argument is in a larger universe such as {anchorTerm SomeTypes}`Type` or even {anchorTerm SomeTypes}`Type 1`.
In particular, this means that predicates over values that have ordinary types are in {anchorTerm PropType}`Prop`.
For example, the type {anchorTerm FunPropType}`(n : Nat) → n = n + 0` represents a function from a {anchorTerm SomeTypes}`Nat` to evidence that it is equal to itself plus zero.
Even though {anchorTerm SomeTypes}`Nat` is in {anchorTerm SomeTypes}`Type`, this function type is in {anchorTerm FunPropType}`Prop` due to this rule.
Similarly, even though {anchorTerm SomeTypes}`Type` is in {anchorTerm SomeTypes}`Type 1`, the function type {anchorTerm FunTypePropType}`Type → 2 + 2 = 4` is still in {anchorTerm FunTypePropType}`Prop`.
# User Defined Types
%%%
tag := "inductive-type-universes"
%%%
Structures and inductive datatypes can be declared to inhabit particular universes.
Lean then checks whether each datatype avoids paradoxes by being in a universe that's large enough to prevent it from containing its own type.
For instance, in the following declaration, {anchorName MyList1}`MyList` is declared to reside in {anchorTerm SomeTypes}`Type`, and so is its type argument {anchorName MyList1}`α`:
```anchor MyList1
inductive MyList (α : Type) : Type where
| nil : MyList α
| cons : α → MyList α → MyList α
```
{anchorTerm MyList1Type}`MyList` itself is a {anchorTerm MyList1Type}`Type → Type`.
This means that it cannot be used to contain actual types, because then its argument would be {anchorTerm SomeTypes}`Type`, which is a {anchorTerm SomeTypes}`Type 1`:
```anchor myListNat1Err
def myListOfNat : MyList Type :=
.cons Nat .nil
```
```anchorError myListNat1Err
Application type mismatch: The argument
Type
has type
Type 1
of sort `Type 2` but is expected to have type
Type
of sort `Type 1` in the application
MyList Type
```
Updating {anchorName MyList2}`MyList` so that its argument is a {anchorTerm MyList2}`Type 1` results in a definition rejected by Lean:
```anchor MyList2
inductive MyList (α : Type 1) : Type where
| nil : MyList α
| cons : α → MyList α → MyList α
```
```anchorError MyList2
Invalid universe level in constructor `MyList.cons`: Parameter has type
α
at universe level
2
which is not less than or equal to the inductive type's resulting universe level
1
```
This error occurs because the argument to {anchorTerm MyList2}`cons` with type {anchorName MyList2}`α` is from a larger universe than {anchorName MyList2}`MyList`.
Placing {anchorName MyList2}`MyList` itself in {anchorTerm SomeTypes}`Type 1` solves this issue, but at the cost of {anchorName MyList2}`MyList` now being itself inconvenient to use in contexts that expect a {anchorTerm SomeTypes}`Type`.
The specific rules that govern whether a datatype is allowed are somewhat complicated.
Generally speaking, it's easiest to start with the datatype in the same universe as the largest of its arguments.
Then, if Lean rejects the definition, increase its level by one, which will usually go through.
# Universe Polymorphism
%%%
tag := "universe-polymorphism"
%%%
Defining a datatype in a specific universe can lead to code duplication.
Placing {anchorName MyList1}`MyList` in {anchorTerm MyList1Type}`Type → Type` means that it can't be used for an actual list of types.
Placing it in {anchorTerm MyList15Type}`Type 1 → Type 1` means that it can't be used for a list of lists of types.
Rather than copy-pasting the datatype to create versions in {anchorTerm SomeTypes}`Type`, {anchorTerm SomeTypes}`Type 1`, {anchorTerm Type2Type}`Type 2`, and so on, a feature called _universe polymorphism_ can be used to write a single definition that can be instantiated in any of these universes.
Ordinary polymorphic types use variables to stand for types in a definition.
This allows Lean to fill in the variables differently, which enables these definitions to be used with a variety of types.
Similarly, universe polymorphism allows variables to stand for universes in a definition, enabling Lean to fill them in differently so that they can be used with a variety of universes.
Just as type arguments are conventionally named with Greek letters, universe arguments are conventionally named {lit}`u`, {lit}`v`, and {lit}`w`.
This definition of {anchorName MyList3}`MyList` doesn't specify a particular universe level, but instead uses a variable {anchorTerm MyList3}`u` to stand for any level.
If the resulting datatype is used with {anchorTerm SomeTypes}`Type`, then {anchorTerm MyList3}`u` is {lit}`0`, and if it's used with {anchorTerm Fun12Type}`Type 3`, then {anchorTerm MyList3}`u` is {lit}`3`:
```anchor MyList3
inductive MyList (α : Type u) : Type u where
| nil : MyList α
| cons : α → MyList α → MyList α
```
With this definition, the same definition of {anchorName MyList3}`MyList` can be used to contain both actual natural numbers and the natural number type itself:
```anchor myListOfNat3
def myListOfNumbers : MyList Nat :=
.cons 0 (.cons 1 .nil)
def myListOfNat : MyList Type :=
.cons Nat .nil
```
It can even contain itself:
```anchor myListOfList3
def myListOfList : MyList (Type → Type) :=
.cons MyList .nil
```
It would seem that this would make it possible to write a logical paradox.
After all, the whole point of the universe system is to rule out self-referential types.
Behind the scenes, however, each occurrence of {anchorName MyList3}`MyList` is provided with a universe level argument.
In essence, the universe-polymorphic definition of {anchorName MyList3}`MyList` created a _copy_ of the datatype at each level, and the level argument selects which copy is to be used.
These level arguments are written with a dot and curly braces, so {anchorTerm MyListDotZero}`MyList.{0} : Type → Type`, {anchorTerm MyListDotOne}`MyList.{1} : Type 1 → Type 1`, and {anchorTerm MyListDotTwo}`MyList.{2} : Type 2 → Type 2`.
Writing the levels explicitly, the prior example becomes:
```anchor myListOfList3Expl
def myListOfNumbers : MyList.{0} Nat :=
.cons 0 (.cons 1 .nil)
def myListOfNat : MyList.{1} Type :=
.cons Nat .nil
def myListOfList : MyList.{1} (Type → Type) :=
.cons MyList.{0} .nil
```
When a universe-polymorphic definition takes multiple types as arguments, it's a good idea to give each argument its own level variable for maximum flexibility.
For example, a version of {anchorName SumNoMax}`Sum` with a single level argument can be written as follows:
```anchor SumNoMax
inductive Sum (α : Type u) (β : Type u) : Type u where
| inl : α → Sum α β
| inr : β → Sum α β
```
This definition can be used at multiple levels:
```anchor SumPoly
def stringOrNat : Sum String Nat := .inl "hello"
def typeOrType : Sum Type Type := .inr Nat
```
However, it requires that both arguments be in the same universe:
```anchor stringOrTypeLevels
def stringOrType : Sum String Type := .inr Nat
```
```anchorError stringOrTypeLevels
Application type mismatch: The argument
Type
has type
Type 1
of sort `Type 2` but is expected to have type
Type
of sort `Type 1` in the application
Sum String Type
```
This datatype can be made more flexible by using different variables for the two type arguments' universe levels, and then declaring that the resulting datatype is in the largest of the two:
```anchor SumMax
inductive Sum (α : Type u) (β : Type v) : Type (max u v) where
| inl : α → Sum α β
| inr : β → Sum α β
```
This allows {anchorName SumMax}`Sum` to be used with arguments from different universes:
```anchor stringOrTypeSum
def stringOrType : Sum String Type := .inr Nat
```
In positions where Lean expects a universe level, any of the following are allowed:
* A concrete level, like {lit}`0` or {lit}`1`
* A variable that stands for a level, such as {anchorTerm SumMax}`u` or {anchorTerm SumMax}`v`
* The maximum of two levels, written as {anchorTerm SumMax}`max` applied to the levels
* A level increase, written with {anchorTerm someTrueProps}`+ 1`
## Writing Universe-Polymorphic Definitions
%%%
tag := none
%%%
Until now, every datatype defined in this book has been in {anchorTerm SomeTypes}`Type`, the smallest universe of data.
When presenting polymorphic datatypes from the Lean standard library, such as {anchorName SomeTypes}`List` and {anchorName SumMax}`Sum`, this book created non-universe-polymorphic versions of them.
The real versions use universe polymorphism to enable code re-use between type-level and non-type-level programs.
There are a few general guidelines to follow when writing universe-polymorphic types.
First off, independent type arguments should have different universe variables, which enables the polymorphic definition to be used with a wider variety of arguments, increasing the potential for code reuse.
Secondly, the whole type is itself typically either in the maximum of all the universe variables, or one greater than this maximum.
Try the smaller of the two first.
Finally, it's a good idea to put the new type in as small of a universe as possible, which allows it to be used more flexibly in other contexts.
Non-polymorphic types, such as {anchorTerm SomeTypes}`Nat` and {anchorName SomeTypes}`String`, can be placed directly in {anchorTerm Type0Type}`Type 0`.
## {anchorTerm PropType}`Prop` and Polymorphism
%%%
tag := none
%%%
Just as {anchorTerm SomeTypes}`Type`, {anchorTerm SomeTypes}`Type 1`, and so on describe types that classify programs and data, {anchorTerm PropType}`Prop` classifies logical propositions.
A type in {anchorTerm PropType}`Prop` describes what counts as convincing evidence for the truth of a statement.
Propositions are like ordinary types in many ways: they can be declared inductively, they can have constructors, and functions can take propositions as arguments.
However, unlike datatypes, it typically doesn't matter _which_ evidence is provided for the truth of a statement, only _that_ evidence is provided.
On the other hand, it is very important that a program not only return a {anchorTerm SomeTypes}`Nat`, but that it's the _correct_ {anchorTerm SomeTypes}`Nat`.
{anchorTerm PropType}`Prop` is at the bottom of the universe hierarchy, and the type of {anchorTerm PropType}`Prop` is {anchorTerm SomeTypes}`Type`.
This means that {anchorTerm PropType}`Prop` is a suitable argument to provide to {anchorName SomeTypes}`List`, for the same reason that {anchorTerm SomeTypes}`Nat` is.
Lists of propositions have type {anchorTerm SomeTypes}`List Prop`:
```anchor someTrueProps
def someTruePropositions : List Prop := [
1 + 1 = 2,
"Hello, " ++ "world!" = "Hello, world!"
]
```
Filling out the universe argument explicitly demonstrates that {anchorTerm PropType}`Prop` is a {anchorTerm SomeTypes}`Type`:
```anchor someTruePropsExp
def someTruePropositions : List.{0} Prop := [
1 + 1 = 2,
"Hello, " ++ "world!" = "Hello, world!"
]
```
Behind the scenes, {anchorTerm PropType}`Prop` and {anchorTerm SomeTypes}`Type` are united into a single hierarchy called {anchorTerm SomeTypes}`Sort`.
{anchorTerm PropType}`Prop` is the same as {anchorTerm sorts}`Sort 0`, {anchorTerm Type0Type}`Type 0` is {anchorTerm sorts}`Sort 1`, {anchorTerm SomeTypes}`Type 1` is {anchorTerm sorts}`Sort 2`, and so forth.
In fact, {anchorTerm sorts}`Type u` is the same as {anchorTerm sorts}`Sort (u+1)`.
When writing programs with Lean, this is typically not relevant, but it may occur in error messages from time to time, and it explains the name of the {anchorName sorts}`CoeSort` class.
Additionally, having {anchorTerm PropType}`Prop` as {anchorTerm sorts}`Sort 0` allows one more universe operator to become useful.
The universe level {lit}`imax u v` is {lit}`0` when {anchorTerm sorts}`v` is {lit}`0`, or the larger of {anchorTerm sorts}`u` or {anchorTerm sorts}`v` otherwise.
Together with {anchorTerm sorts}`Sort`, this allows the special rule for functions that return {anchorTerm PropType}`Prop`s to be used when writing code that should be as portable as possible between {anchorTerm PropType}`Prop` and {anchorTerm SomeTypes}`Type` universes.
# Polymorphism in Practice
%%%
tag := none
%%%
In the remainder of the book, definitions of polymorphic datatypes, structures, and classes will use universe polymorphism in order to be consistent with the Lean standard library.
This will enable the complete presentation of the {moduleName}`Functor`, {anchorName next}`Applicative`, and {anchorName next}`Monad` classes to be completely consistent with their actual definitions. |
fp-lean/book/FPLean/FunctorApplicativeMonad/Summary.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.FunctorApplicativeMonad.ActualDefs"
#doc (Manual) "Summary" =>
%%%
tag := "structure-applicative-monad-summary"
%%%
# Type Classes and Structures
%%%
tag := none
%%%
Behind the scenes, type classes are represented by structures.
Defining a class defines a structure, and additionally creates an empty table of instances.
Defining an instance creates a value that either has the structure as its type or is a function that can return the structure, and additionally adds an entry to the table.
Instance search consists of constructing an instance by consulting the instance tables.
Both structures and classes may provide default values for fields (which are default implementations of methods).
# Structures and Inheritance
%%%
tag := none
%%%
Structures may inherit from other structures.
Behind the scenes, a structure that inherits from another structure contains an instance of the original structure as a field.
In other words, inheritance is implemented with composition.
When multiple inheritance is used, only the unique fields from the additional parent structures are used to avoid a diamond problem, and the functions that would normally extract the parent value are instead organized to construct one.
Record dot notation takes structure inheritance into account.
Because type classes are just structures with some additional automation applied, all of these features are available in type classes.
Together with default methods, this can be used to create a fine-grained hierarchy of interfaces that nonetheless does not impose a large burden on clients, because the small classes that the large classes inherit from can be automatically implemented.
# Applicative Functors
%%%
tag := none
%%%
An applicative functor is a functor with two additional operations:
* {anchorName Applicative}`pure`, which is the same operator as that for {anchorName Monad}`Monad`
* {anchorName Seq}`seq`, which allows a function to be applied in the context of the functor.
While monads can represent arbitrary programs with control flow, applicative functors can only run function arguments from left to right.
Because they are less powerful, they provide less control to programs written against the interface, while the implementor of the method has a greater degree of freedom.
Some useful types can implement {anchorName Applicative}`Applicative` but not {anchorName Monad}`Monad`.
In fact, the type classes {anchorName HonestFunctor}`Functor`, {anchorName Applicative}`Applicative`, and {anchorName Monad}`Monad` form a hierarchy of power.
Moving up the hierarchy, from {anchorName HonestFunctor}`Functor` towards {anchorName Monad}`Monad`, allows more powerful programs to be written, but fewer types implement the more powerful classes.
Polymorphic programs should be written to use as weak of an abstraction as possible, while datatypes should be given instances that are as powerful as possible.
This maximizes code re-use.
The more powerful type classes extend the less powerful ones, which means that an implementation of {anchorName Monad}`Monad` provides implementations of {anchorName HonestFunctor}`Functor` and {anchorName Applicative}`Applicative` for free.
Each class has a set of methods to be implemented and a corresponding contract that specifies additional rules for the methods.
Programs that are written against these interfaces expect that the additional rules are followed, and may be buggy if they are not.
The default implementations of {anchorName HonestFunctor}`Functor`'s methods in terms of {anchorName Applicative}`Applicative`'s, and of {anchorName Applicative}`Applicative`'s in terms of {anchorName Monad}`Monad`'s, will obey these rules.
# Universes
%%%
tag := none
%%%
To allow Lean to be used as both a programming language and a theorem prover, some restrictions on the language are necessary.
This includes restrictions on recursive functions that ensure that they all either terminate or are marked as {kw}`partial` and written to return types that are not uninhabited.
Additionally, it must be impossible to represent certain kinds of logical paradoxes as types.
One of the restrictions that rules out certain paradoxes is that every type is assigned to a _universe_.
Universes are types such as {anchorTerm extras}`Prop`, {anchorTerm extras}`Type`, {anchorTerm extras}`Type 1`, {anchorTerm extras}`Type 2`, and so forth.
These types describe other types—just as {anchorTerm extras}`0` and {anchorTerm extras}`17` are described by {anchorName extras}`Nat`, {anchorName extras}`Nat` is itself described by {anchorTerm extras}`Type`, and {anchorTerm extras}`Type` is described by {anchorTerm extras}`Type 1`.
The type of functions that take a type as an argument must be a larger universe than the argument's universe.
Because each declared datatype has a universe, writing code that uses types like data would quickly become annoying, requiring each polymorphic type to be copy-pasted to take arguments from {anchorTerm extras}`Type 1`.
A feature called _universe polymorphism_ allows Lean programs and datatypes to take universe levels as arguments, just as ordinary polymorphism allows programs to take types as arguments.
Generally speaking, Lean libraries should use universe polymorphism when implementing libraries of polymorphic operations. |
fp-lean/book/FPLean/FunctorApplicativeMonad/Alternative.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.FunctorApplicativeMonad"
#doc (Manual) "Alternatives" =>
%%%
tag := "alternative"
%%%
# Recovery from Failure
%%%
tag := "alternative-recovery"
%%%
{anchorName Validate}`Validate` can also be used in situations where there is more than one way for input to be acceptable.
For the input form {anchorName RawInput}`RawInput`, an alternative set of business rules that implement conventions from a legacy system might be the following:
1. All human users must provide a birth year that is four digits.
2. Users born prior to 1970 do not need to provide names, due to incomplete older records.
3. Users born after 1970 must provide names.
4. Companies should enter {anchorTerm checkCompany}`"FIRM"` as their year of birth and provide a company name.
No particular provision is made for users born in 1970.
It is expected that they will either give up, lie about their year of birth, or call.
The company considers this an acceptable cost of doing business.
The following inductive type captures the values that can be produced from these stated rules:
```anchor LegacyCheckedInput
abbrev NonEmptyString := {s : String // s ≠ ""}
inductive LegacyCheckedInput where
| humanBefore1970 :
(birthYear : {y : Nat // y > 999 ∧ y < 1970}) →
String →
LegacyCheckedInput
| humanAfter1970 :
(birthYear : {y : Nat // y > 1970}) →
NonEmptyString →
LegacyCheckedInput
| company :
NonEmptyString →
LegacyCheckedInput
deriving Repr
```
A validator for these rules is more complicated, however, as it must address all three cases.
While it can be written as a series of nested {kw}`if` expressions, it's easier to design the three cases independently and then combine them.
This requires a means of recovering from failure while preserving error messages:
```anchor ValidateorElse
def Validate.orElse
(a : Validate ε α)
(b : Unit → Validate ε α) :
Validate ε α :=
match a with
| .ok x => .ok x
| .errors errs1 =>
match b () with
| .ok x => .ok x
| .errors errs2 => .errors (errs1 ++ errs2)
```
This pattern of recovery from failures is common enough that Lean has built-in syntax for it, attached to a type class named {anchorName OrElse}`OrElse`:
```anchor OrElse
class OrElse (α : Type) where
orElse : α → (Unit → α) → α
```
The expression {anchorTerm OrElseSugar}`E1 <|> E2` is short for {anchorTerm OrElseSugar}`OrElse.orElse E1 (fun () => E2)`.
An instance of {anchorName OrElse}`OrElse` for {anchorName Validate}`Validate` allows this syntax to be used for error recovery:
```anchor OrElseValidate
instance : OrElse (Validate ε α) where
orElse := Validate.orElse
```
The validator for {anchorName LegacyCheckedInput}`LegacyCheckedInput` can be built from a validator for each constructor.
The rules for a company state that the birth year should be the string {anchorTerm checkCompany}`"FIRM"` and that the name should be non-empty.
The constructor {anchorName names1}`LegacyCheckedInput.company`, however, has no representation of the birth year at all, so there's no easy way to carry it out using {anchorTerm checkCompanyProv}`<*>`.
The key is to use a function with {anchorTerm checkCompanyProv}`<*>` that ignores its argument.
Checking that a Boolean condition holds without recording any evidence of this fact in a type can be accomplished with {anchorName checkThat}`checkThat`:
```anchor checkThat
def checkThat (condition : Bool)
(field : Field) (msg : String) :
Validate (Field × String) Unit :=
if condition then pure () else reportError field msg
```
This definition of {anchorName checkCompanyProv}`checkCompany` uses {anchorName checkCompanyProv}`checkThat`, and then throws away the resulting {anchorName checkThat}`Unit` value:
```anchor checkCompanyProv
def checkCompany (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
pure (fun () name => .company name) <*>
checkThat (input.birthYear == "FIRM")
"birth year" "FIRM if a company" <*>
checkName input.name
```
However, this definition is quite noisy.
It can be simplified in two ways.
The first is to replace the first use of {anchorTerm checkCompanyProv}`<*>` with a specialized version that automatically ignores the value returned by the first argument, called {anchorTerm checkCompany}`*>`.
This operator is also controlled by a type class, called {anchorName ClassSeqRight}`SeqRight`, and {anchorTerm seqRightSugar}`E1 *> E2` is syntactic sugar for {anchorTerm seqRightSugar}`SeqRight.seqRight E1 (fun () => E2)`:
```anchor ClassSeqRight
class SeqRight (f : Type → Type) where
seqRight : f α → (Unit → f β) → f β
```
There is a default implementation of {anchorName ClassSeqRight}`seqRight` in terms of {anchorName fakeSeq}`seq`: {lit}`seqRight (a : f α) (b : Unit → f β) : f β := pure (fun _ x => x) <*> a <*> b ()`.
Using {anchorName ClassSeqRight}`seqRight`, {anchorName checkCompanyProv2}`checkCompany` becomes simpler:
```anchor checkCompanyProv2
def checkCompany (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
checkThat (input.birthYear == "FIRM")
"birth year" "FIRM if a company" *>
pure .company <*> checkName input.name
```
One more simplification is possible.
For every {anchorName ApplicativeExcept}`Applicative`, {anchorTerm ApplicativeLaws}`pure f <*> E` is equivalent to {anchorTerm ApplicativeLaws}`f <$> E`.
In other words, using {anchorName fakeSeq}`seq` to apply a function that was placed into the {anchorName ApplicativeExtendsFunctorOne}`Applicative` type using {anchorName ApplicativeExtendsFunctorOne}`pure` is overkill, and the function could have just been applied using {anchorName ApplicativeLaws}`Functor.map`.
This simplification yields:
```anchor checkCompany
def checkCompany (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
checkThat (input.birthYear == "FIRM")
"birth year" "FIRM if a company" *>
.company <$> checkName input.name
```
The remaining two constructors of {anchorName LegacyCheckedInput}`LegacyCheckedInput` use subtypes for their fields.
A general-purpose tool for checking subtypes will make these easier to read:
```anchor checkSubtype
def checkSubtype {α : Type} (v : α) (p : α → Prop) [Decidable (p v)]
(err : ε) : Validate ε {x : α // p x} :=
if h : p v then
pure ⟨v, h⟩
else
.errors { head := err, tail := [] }
```
In the function's argument list, it's important that the type class {anchorTerm checkSubtype}`[Decidable (p v)]` occur after the specification of the arguments {anchorName checkSubtype}`v` and {anchorName checkSubtype}`p`.
Otherwise, it would refer to an additional set of automatic implicit arguments, rather than to the manually-provided values.
The {anchorName checkSubtype}`Decidable` instance is what allows the proposition {anchorTerm checkSubtype}`p v` to be checked using {kw}`if`.
The two human cases do not need any additional tools:
```anchor checkHumanBefore1970
def checkHumanBefore1970 (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
(checkYearIsNat input.birthYear).andThen fun y =>
.humanBefore1970 <$>
checkSubtype y (fun x => x > 999 ∧ x < 1970)
("birth year", "less than 1970") <*>
pure input.name
```
```anchor checkHumanAfter1970
def checkHumanAfter1970 (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
(checkYearIsNat input.birthYear).andThen fun y =>
.humanAfter1970 <$>
checkSubtype y (· > 1970)
("birth year", "greater than 1970") <*>
checkName input.name
```
The validators for the three cases can be combined using {anchorTerm OrElseSugar}`<|>`:
```anchor checkLegacyInput
def checkLegacyInput (input : RawInput) :
Validate (Field × String) LegacyCheckedInput :=
checkCompany input <|>
checkHumanBefore1970 input <|>
checkHumanAfter1970 input
```
The successful cases return constructors of {anchorName LegacyCheckedInput}`LegacyCheckedInput`, as expected:
```anchor trollGroomers
#eval checkLegacyInput ⟨"Johnny's Troll Groomers", "FIRM"⟩
```
```anchorInfo trollGroomers
Validate.ok (LegacyCheckedInput.company "Johnny's Troll Groomers")
```
```anchor johnny
#eval checkLegacyInput ⟨"Johnny", "1963"⟩
```
```anchorInfo johnny
Validate.ok (LegacyCheckedInput.humanBefore1970 1963 "Johnny")
```
```anchor johnnyAnon
#eval checkLegacyInput ⟨"", "1963"⟩
```
```anchorInfo johnnyAnon
Validate.ok (LegacyCheckedInput.humanBefore1970 1963 "")
```
The worst possible input returns all the possible failures:
```anchor allFailures
#eval checkLegacyInput ⟨"", "1970"⟩
```
```anchorInfo allFailures
Validate.errors
{ head := ("birth year", "FIRM if a company"),
tail := [("name", "Required"),
("birth year", "less than 1970"),
("birth year", "greater than 1970"),
("name", "Required")] }
```
# The {lit}`Alternative` Class
%%%
tag := "Alternative"
%%%
Many types support a notion of failure and recovery.
The {anchorName AlternativeMany}`Many` monad from the section on {ref "nondeterministic-search"}[evaluating arithmetic expressions in a variety of monads] is one such type, as is {anchorName AlternativeOption}`Option`.
Both support failure without providing a reason (unlike, say, {anchorName ApplicativeExcept}`Except` and {anchorName Validate}`Validate`, which require some indication of what went wrong).
The {anchorName FakeAlternative}`Alternative` class describes applicative functors that have additional operators for failure and recovery:
```anchor FakeAlternative
class Alternative (f : Type → Type) extends Applicative f where
failure : f α
orElse : f α → (Unit → f α) → f α
```
Just as implementors of {anchorTerm misc}`Add α` get {anchorTerm misc}`HAdd α α α` instances for free, implementors of {anchorName FakeAlternative}`Alternative` get {anchorName OrElse}`OrElse` instances for free:
```anchor AltOrElse
instance [Alternative f] : OrElse (f α) where
orElse := Alternative.orElse
```
The implementation of {anchorName FakeAlternative}`Alternative` for {anchorName ApplicativeOption}`Option` keeps the first non-{anchorName ApplicativeOption}`none` argument:
```anchor AlternativeOption
instance : Alternative Option where
failure := none
orElse
| some x, _ => some x
| none, y => y ()
```
Similarly, the implementation for {anchorName AlternativeMany}`Many` follows the general structure of {moduleName (module := Examples.Monads.Many)}`Many.union`, with minor differences due to the laziness-inducing {anchorName guard}`Unit` parameters being placed differently:
```anchor AlternativeMany
def Many.orElse : Many α → (Unit → Many α) → Many α
| .none, ys => ys ()
| .more x xs, ys => .more x (fun () => orElse (xs ()) ys)
instance : Alternative Many where
failure := .none
orElse := Many.orElse
```
Like other type classes, {anchorName FakeAlternative}`Alternative` enables the definition of a variety of operations that work for _any_ applicative functor that implements {anchorName FakeAlternative}`Alternative`.
One of the most important is {anchorName guard}`guard`, which causes {anchorName guard}`failure` when a decidable proposition is false:
```anchor guard
def guard [Alternative f] (p : Prop) [Decidable p] : f Unit :=
if p then
pure ()
else failure
```
It is very useful in monadic programs to terminate execution early.
In {anchorName evenDivisors}`Many`, it can be used to filter out a whole branch of a search, as in the following program that computes all even divisors of a natural number:
```anchor evenDivisors
def Many.countdown : Nat → Many Nat
| 0 => .none
| n + 1 => .more n (fun () => countdown n)
def evenDivisors (n : Nat) : Many Nat := do
let k ← Many.countdown (n + 1)
guard (k % 2 = 0)
guard (n % k = 0)
pure k
```
Running it on {anchorTerm evenDivisors20}`20` yields the expected results:
```anchor evenDivisors20
#eval (evenDivisors 20).takeAll
```
```anchorInfo evenDivisors20
[20, 10, 4, 2]
```
# Exercises
%%%
tag := "Alternative-exercises"
%%%
## Improve Validation Friendliness
%%%
tag := none
%%%
The errors returned from {anchorName Validate}`Validate` programs that use {anchorTerm OrElseSugar}`<|>` can be difficult to read, because inclusion in the list of errors simply means that the error can be reached through _some_ code path.
A more structured error report can be used to guide the user through the process more accurately:
* Replace the {anchorName Validate}`NonEmptyList` in {anchorName misc}`Validate.errors` with a bare type variable, and then update the definitions of the {anchorTerm ApplicativeValidate}`Applicative (Validate ε)` and {anchorTerm OrElseValidate}`OrElse (Validate ε α)` instances to require only that there be an {anchorTerm misc}`Append ε` instance available.
* Define a function {anchorTerm misc}`Validate.mapErrors : Validate ε α → (ε → ε') → Validate ε' α` that transforms all the errors in a validation run.
* Using the datatype {anchorName TreeError}`TreeError` to represent errors, rewrite the legacy validation system to track its path through the three alternatives.
* Write a function {anchorTerm misc}`report : TreeError → String` that outputs a user-friendly view of the {anchorName TreeError}`TreeError`'s accumulated warnings and errors.
```anchor TreeError
inductive TreeError where
| field : Field → String → TreeError
| path : String → TreeError → TreeError
| both : TreeError → TreeError → TreeError
instance : Append TreeError where
append := .both
``` |
fp-lean/book/FPLean/FunctorApplicativeMonad/Inheritance.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso Code External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.FunctorApplicativeMonad"
#doc (Manual) "Structures and Inheritance" =>
%%%
tag := "structure-inheritance"
%%%
In order to understand the full definitions of {anchorName ApplicativeLaws}`Functor`, {anchorName ApplicativeLaws}`Applicative`, and {anchorName ApplicativeLaws}`Monad`, another Lean feature is necessary: structure inheritance.
Structure inheritance allows one structure type to provide the interface of another, along with additional fields.
This can be useful when modeling concepts that have a clear taxonomic relationship.
For example, take a model of mythical creatures.
Some of them are large, and some are small:
```anchor MythicalCreature
structure MythicalCreature where
large : Bool
deriving Repr
```
Behind the scenes, defining the {anchorName MythicalCreature}`MythicalCreature` structure creates an inductive type with a single constructor called {anchorName MythicalCreatureMore}`mk`:
```anchor MythicalCreatureMk
#check MythicalCreature.mk
```
```anchorInfo MythicalCreatureMk
MythicalCreature.mk (large : Bool) : MythicalCreature
```
Similarly, a function {anchorName MythicalCreatureLarge}`MythicalCreature.large` is created that actually extracts the field from the constructor:
```anchor MythicalCreatureLarge
#check MythicalCreature.large
```
```anchorInfo MythicalCreatureLarge
MythicalCreature.large (self : MythicalCreature) : Bool
```
In most old stories, each monster can be defeated in some way.
A description of a monster should include this information, along with whether it is large:
```anchor Monster
structure Monster extends MythicalCreature where
vulnerability : String
deriving Repr
```
The {anchorTerm Monster}`extends MythicalCreature` in the heading states that every monster is also mythical.
To define a {anchorName Monster}`Monster`, both the fields from {anchorName Monster}`MythicalCreature` and the fields from {anchorName Monster}`Monster` should be provided.
A troll is a large monster that is vulnerable to sunlight:
```anchor troll
def troll : Monster where
large := true
vulnerability := "sunlight"
```
Behind the scenes, inheritance is implemented using composition.
The constructor {anchorName MonsterMk}`Monster.mk` takes a {anchorName Monster}`MythicalCreature` as its argument:
```anchor MonsterMk
#check Monster.mk
```
```anchorInfo MonsterMk
Monster.mk (toMythicalCreature : MythicalCreature) (vulnerability : String) : Monster
```
In addition to defining functions to extract the value of each new field, a function {anchorTerm MonsterToCreature}`Monster.toMythicalCreature` is defined with type {anchorTerm MonsterToCreature}`Monster → MythicalCreature`.
This can be used to extract the underlying creature.
Moving up the inheritance hierarchy in Lean is not the same thing as upcasting in object-oriented languages.
An upcast operator causes a value from a derived class to be treated as an instance of the parent class, but the value retains its identity and structure.
In Lean, however, moving up the inheritance hierarchy actually erases the underlying information.
To see this in action, consider the result of evaluating {anchorTerm evalTrollCast}`troll.toMythicalCreature`:
```anchor evalTrollCast
#eval troll.toMythicalCreature
```
```anchorInfo evalTrollCast
{ large := true }
```
Only the fields of {anchorName MythicalCreature}`MythicalCreature` remain.
Just like the {kw}`where` syntax, curly-brace notation with field names also works with structure inheritance:
```anchor troll2
def troll : Monster := {large := true, vulnerability := "sunlight"}
```
However, the anonymous angle-bracket notation that delegates to the underlying constructor reveals the internal details:
```anchor wrongTroll1
def troll : Monster := ⟨true, "sunlight"⟩
```
```anchorError wrongTroll1
Application type mismatch: The argument
true
has type
Bool
but is expected to have type
MythicalCreature
in the application
Monster.mk true
```
An extra set of angle brackets is required, which invokes {anchorName MythicalCreatureMk}`MythicalCreature.mk` on {anchorName troll3}`true`:
```anchor troll3
def troll : Monster := ⟨⟨true⟩, "sunlight"⟩
```
Lean's dot notation is capable of taking inheritance into account.
In other words, the existing {anchorName trollLargeNoDot}`MythicalCreature.large` can be used with a {anchorName Monster}`Monster`, and Lean automatically inserts the call to {anchorTerm MonsterToCreature}`Monster.toMythicalCreature` before the call to {anchorName trollLargeNoDot}`MythicalCreature.large`.
However, this only occurs when using dot notation, and applying the field lookup function using normal function call syntax results in a type error:
```anchor trollLargeNoDot
#eval MythicalCreature.large troll
```
```anchorError trollLargeNoDot
Application type mismatch: The argument
troll
has type
Monster
but is expected to have type
MythicalCreature
in the application
MythicalCreature.large troll
```
Dot notation can also take inheritance into account for user-defined functions.
A small creature is one that is not large:
```anchor small
def MythicalCreature.small (c : MythicalCreature) : Bool := !c.large
```
Evaluating {anchorTerm smallTroll}`troll.small` yields {anchorTerm smallTroll}`false`, while attempting to evaluate {anchorTerm smallTrollWrong}`MythicalCreature.small troll` results in:
```anchorError smallTrollWrong
Application type mismatch: The argument
troll
has type
Monster
but is expected to have type
MythicalCreature
in the application
MythicalCreature.small troll
```
# Multiple Inheritance
%%%
tag := "multiple-structure-inheritance"
%%%
A helper is a mythical creature that can provide assistance when given the correct payment:
```anchor Helper
structure Helper extends MythicalCreature where
assistance : String
payment : String
deriving Repr
```
For example, a _nisse_ is a kind of small elf that's known to help around the house when provided with tasty porridge:
```anchor elf
def nisse : Helper where
large := false
assistance := "household tasks"
payment := "porridge"
```
If domesticated, trolls make excellent helpers.
They are strong enough to plow a whole field in a single night, though they require model goats to keep them satisfied with their lot in life.
A monstrous assistant is a monster that is also a helper:
```anchor MonstrousAssistant
structure MonstrousAssistant extends Monster, Helper where
deriving Repr
```
A value of this structure type must fill in all of the fields from both parent structures:
```anchor domesticatedTroll
def domesticatedTroll : MonstrousAssistant where
large := true
assistance := "heavy labor"
payment := "toy goats"
vulnerability := "sunlight"
```
Both of the parent structure types extend {anchorName MythicalCreature}`MythicalCreature`.
If multiple inheritance were implemented naïvely, then this could lead to a “diamond problem”, where it would be unclear which path to {anchorName MythicalCreature}`large` should be taken from a given {anchorName MonstrousAssistant}`MonstrousAssistant`.
Should it take {lit}`large` from the contained {anchorName Monster}`Monster` or from the contained {anchorName Helper}`Helper`?
In Lean, the answer is that the first specified path to the grandparent structure is taken, and the additional parent structures' fields are copied rather than having the new structure include both parents directly.
This can be seen by examining the signature of the constructor for {anchorName MonstrousAssistant}`MonstrousAssistant`:
```anchor checkMonstrousAssistantMk
#check MonstrousAssistant.mk
```
```anchorInfo checkMonstrousAssistantMk
MonstrousAssistant.mk (toMonster : Monster) (assistance payment : String) : MonstrousAssistant
```
It takes a {anchorName Monster}`Monster` as an argument, along with the two fields that {anchorName Helper}`Helper` introduces on top of {anchorName MythicalCreature}`MythicalCreature`.
Similarly, while {anchorName MonstrousAssistantMore}`MonstrousAssistant.toMonster` merely extracts the {anchorName Monster}`Monster` from the constructor, {anchorName printMonstrousAssistantToHelper}`MonstrousAssistant.toHelper` has no {anchorName Helper}`Helper` to extract.
The {kw}`#print` command exposes its implementation:
```anchor printMonstrousAssistantToHelper
#print MonstrousAssistant.toHelper
```
```anchorInfo printMonstrousAssistantToHelper
@[reducible] def MonstrousAssistant.toHelper : MonstrousAssistant → Helper :=
fun self => { toMythicalCreature := self.toMythicalCreature, assistance := self.assistance, payment := self.payment }
```
This function constructs a {anchorName Helper}`Helper` from the fields of {anchorName MonstrousAssistant}`MonstrousAssistant`.
The {lit}`@[reducible]` attribute has the same effect as writing {kw}`abbrev`.
## Default Declarations
%%%
tag := "inheritance-defaults"
%%%
When one structure inherits from another, default field definitions can be used to instantiate the parent structure's fields based on the child structure's fields.
If more size specificity is required than whether a creature is large or not, a dedicated datatype describing sizes can be used together with inheritance, yielding a structure in which the {anchorName MythicalCreature}`large` field is computed from the contents of the {anchorName SizedCreature}`size` field:
```anchor SizedCreature
inductive Size where
| small
| medium
| large
deriving BEq
structure SizedCreature extends MythicalCreature where
size : Size
large := size == Size.large
```
This default definition is only a default definition, however.
Unlike property inheritance in a language like C# or Scala, the definitions in the child structure are only used when no specific value for {anchorName MythicalCreature}`large` is provided, and nonsensical results can occur:
```anchor nonsenseCreature
def nonsenseCreature : SizedCreature where
large := false
size := .large
```
If the child structure should not deviate from the parent structure, there are a few options:
1. Documenting the relationship, as is done for {anchorName SizedCreature}`BEq` and {anchorName MonstrousAssistantMore}`Hashable`
2. Defining a proposition that the fields are related appropriately, and designing the API to require evidence that the proposition is true where it matters
3. Not using inheritance at all
The second option could look like this:
```anchor sizesMatch
abbrev SizesMatch (sc : SizedCreature) : Prop :=
sc.large = (sc.size == Size.large)
```
Note that a single equality sign is used to indicate the equality _proposition_, while a double equality sign is used to indicate a function that checks equality and returns a {anchorName MythicalCreature}`Bool`.
{anchorName sizesMatch}`SizesMatch` is defined as an {kw}`abbrev` because it should automatically be unfolded in proofs, so that {tactic}`decide` can see the equality that should be proven.
A _huldre_ is a medium-sized mythical creature—in fact, they are the same size as humans.
The two sized fields on {anchorName huldresize}`huldre` match one another:
```anchor huldresize
def huldre : SizedCreature where
size := .medium
example : SizesMatch huldre := by
decide
```
## Type Class Inheritance
%%%
tag := "type-class-inheritance"
%%%
Behind the scenes, type classes are structures.
Defining a new type class defines a new structure, and defining an instance creates a value of that structure type.
They are then added to internal tables in Lean that allow it to find the instances upon request.
A consequence of this is that type classes may inherit from other type classes.
Because it uses precisely the same language features, type class inheritance supports all the features of structure inheritance, including multiple inheritance, default implementations of parent types' methods, and automatic collapsing of diamonds.
This is useful in many of the same situations that multiple interface inheritance is useful in languages like Java, C# and Kotlin.
By carefully designing type class inheritance hierarchies, programmers can get the best of both worlds: a fine-grained collection of independently-implementable abstractions, and automatic construction of these specific abstractions from larger, more general abstractions. |
fp-lean/book/FPLean/Meta/NameSuffixMap.lean | |
fp-lean/book/FPLean/DependentTypes/TypedQueries.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.DependentTypes.DB"
#doc (Manual) "Worked Example: Typed Queries" =>
%%%
tag := "typed-queries"
%%%
Indexed families are very useful when building an API that is supposed to resemble some other language.
They can be used to write a library of HTML constructors that don't permit generating invalid HTML, to encode the specific rules of a configuration file format, or to model complicated business constraints.
This section describes an encoding of a subset of relational algebra in Lean using indexed families, as a simpler demonstration of techniques that can be used to build a more powerful database query language.
This subset uses the type system to enforce requirements such as disjointness of field names, and it uses type-level computation to reflect the schema into the types of values that are returned from a query.
It is not a realistic system, however—databases are represented as linked lists of linked lists, the type system is much simpler than that of SQL, and the operators of relational algebra don't really match those of SQL.
However, it is large enough to demonstrate useful principles and techniques.
# A Universe of Data
%%%
tag := "typed-query-data-universe"
%%%
In this relational algebra, the base data that can be held in columns can have types {anchorName DBType}`Int`, {anchorName DBType}`String`, and {anchorName DBType}`Bool` and are described by the universe {anchorName DBType}`DBType`:
```anchor DBType
inductive DBType where
| int | string | bool
abbrev DBType.asType : DBType → Type
| .int => Int
| .string => String
| .bool => Bool
```
Using {anchorName DBType}`DBType.asType` allows these codes to be used for types.
For example:
```anchor mountHoodEval
#eval ("Mount Hood" : DBType.string.asType)
```
```anchorInfo mountHoodEval
"Mount Hood"
```
It is possible to compare the values described by any of the three database types for equality.
Explaining this to Lean, however, requires a bit of work.
Simply using {anchorName BEqDBType}`BEq` directly fails:
```anchor dbEqNoSplit
def DBType.beq (t : DBType) (x y : t.asType) : Bool :=
x == y
```
```anchorError dbEqNoSplit
failed to synthesize
BEq t.asType
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
```
Just as in the nested pairs universe, type class search doesn't automatically check each possibility for {anchorName dbEqNoSplit}`t`'s value
The solution is to use pattern matching to refine the types of {anchorTerm dbEq}`x` and {anchorName dbEq}`y`:
```anchor dbEq
def DBType.beq (t : DBType) (x y : t.asType) : Bool :=
match t with
| .int => x == y
| .string => x == y
| .bool => x == y
```
In this version of the function, {anchorName dbEq}`x` and {anchorName dbEq}`y` have types {anchorName DBType}`Int`, {anchorName DBType}`String`, and {anchorName DBType}`Bool` in the three respective cases, and these types all have {anchorName BEqDBType}`BEq` instances.
The definition of {anchorName dbEq}`DBType.beq` can be used to define a {anchorName BEqDBType}`BEq` instance for the types that are coded for by {anchorName DBType}`DBType`:
```anchor BEqDBType
instance {t : DBType} : BEq t.asType where
beq := t.beq
```
This is not the same as an instance for the codes:
```anchor BEqDBTypeCodes
instance : BEq DBType where
beq
| .int, .int => true
| .string, .string => true
| .bool, .bool => true
| _, _ => false
```
The former instance allows comparison of values drawn from the types described by the codes, while the latter allows comparison of the codes themselves.
A {anchorName ReprAsType}`Repr` instance can be written using the same technique.
The method of the {anchorName ReprAsType}`Repr` class is called {anchorName ReprAsType}`reprPrec` because it is designed to take things like operator precedence into account when displaying values.
Refining the type through dependent pattern matching allows the {anchorName ReprAsType}`reprPrec` methods from the {anchorName ReprAsType}`Repr` instances for {anchorName DBType}`Int`, {anchorName DBType}`String`, and {anchorName DBType}`Bool` to be used:
```anchor ReprAsType
instance {t : DBType} : Repr t.asType where
reprPrec :=
match t with
| .int => reprPrec
| .string => reprPrec
| .bool => reprPrec
```
# Schemas and Tables
%%%
tag := "schemas"
%%%
A schema describes the name and type of each column in a database:
```anchor Schema
structure Column where
name : String
contains : DBType
abbrev Schema := List Column
```
In fact, a schema can be seen as a universe that describes rows in a table.
The empty schema describes the unit type, a schema with a single column describes that value on its own, and a schema with at least two columns is represented by a tuple:
```anchor Row
abbrev Row : Schema → Type
| [] => Unit
| [col] => col.contains.asType
| col1 :: col2 :: cols => col1.contains.asType × Row (col2::cols)
```
As described in {ref "prod"}[the initial section on product types], Lean's product type and tuples are right-associative.
This means that nested pairs are equivalent to ordinary flat tuples.
A table is a list of rows that share a schema:
```anchor Table
abbrev Table (s : Schema) := List (Row s)
```
For example, a diary of visits to mountain peaks can be represented with the schema {anchorName peak}`peak`:
```anchor peak
abbrev peak : Schema := [
⟨"name", .string⟩,
⟨"location", .string⟩,
⟨"elevation", .int⟩,
⟨"lastVisited", .int⟩
]
```
A selection of peaks visited by the author of this book appears as an ordinary list of tuples:
```anchor mountainDiary
def mountainDiary : Table peak := [
("Mount Nebo", "USA", 3637, 2013),
("Moscow Mountain", "USA", 1519, 2015),
("Himmelbjerget", "Denmark", 147, 2004),
("Mount St. Helens", "USA", 2549, 2010)
]
```
Another example consists of waterfalls and a diary of visits to them:
```anchor waterfall
abbrev waterfall : Schema := [
⟨"name", .string⟩,
⟨"location", .string⟩,
⟨"lastVisited", .int⟩
]
```
```anchor waterfallDiary
def waterfallDiary : Table waterfall := [
("Multnomah Falls", "USA", 2018),
("Shoshone Falls", "USA", 2014)
]
```
## Recursion and Universes, Revisited
%%%
tag := "recursion-universes-revisited"
%%%
The convenient structuring of rows as tuples comes at a cost: the fact that {anchorName Row}`Row` treats its two base cases separately means that functions that use {anchorName Row}`Row` in their types and are defined recursively over the codes (that, is the schema) need to make the same distinctions.
One example of a case where this matters is an equality check that uses recursion over the schema to define a function that checks rows for equality.
This example does not pass Lean's type checker:
```anchor RowBEqRecursion
def Row.bEq (r1 r2 : Row s) : Bool :=
match s with
| [] => true
| col::cols =>
match r1, r2 with
| (v1, r1'), (v2, r2') =>
v1 == v2 && bEq r1' r2'
```
```anchorError RowBEqRecursion
Type mismatch
(v1, r1')
has type
?m.10 × ?m.11
but is expected to have type
Row (col :: cols)
```
The problem is that the pattern {anchorTerm RowBEqRecursion}`col :: cols` does not sufficiently refine the type of the rows.
This is because Lean cannot yet tell whether the singleton pattern {anchorTerm Row}`[col]` or the {anchorTerm Row}`col1 :: col2 :: cols` pattern in the definition of {anchorName Row}`Row` was matched, so the call to {anchorName Row}`Row` does not compute down to a pair type.
The solution is to mirror the structure of {anchorName Row}`Row` in the definition of {anchorName RowBEq}`Row.bEq`:
```anchor RowBEq
def Row.bEq (r1 r2 : Row s) : Bool :=
match s with
| [] => true
| [_] => r1 == r2
| _::_::_ =>
match r1, r2 with
| (v1, r1'), (v2, r2') =>
v1 == v2 && bEq r1' r2'
instance : BEq (Row s) where
beq := Row.bEq
```
Unlike in other contexts, functions that occur in types cannot be considered only in terms of their input/output behavior.
Programs that use these types will find themselves forced to mirror the algorithm used in the type-level function so that their structure matches the pattern-matching and recursive behavior of the type.
A big part of the skill of programming with dependent types is the selection of appropriate type-level functions with the right computational behavior.
## Column Pointers
%%%
tag := "column-pointers"
%%%
Some queries only make sense if a schema contains a particular column.
For example, a query that returns mountains with an elevation greater than 1000 meters only makes sense in the context of a schema with an {anchorTerm peak}`"elevation"` column that contains integers.
One way to indicate that a column is contained in a schema is to provide a pointer directly to it, and defining the pointer as an indexed family makes it possible to rule out invalid pointers.
There are two ways that a column can be present in a schema: either it is at the beginning of the schema, or it is somewhere later in the schema.
Eventually, if a column is later in a schema, then it will be the beginning of some tail of the schema.
The indexed family {anchorName HasCol}`HasCol` is a translation of the specification into Lean code:
```anchor HasCol
inductive HasCol : Schema → String → DBType → Type where
| here : HasCol (⟨name, t⟩ :: _) name t
| there : HasCol s name t → HasCol (_ :: s) name t
```
The family's three arguments are the schema, the column name, and its type.
All three are indices, but re-ordering the arguments to place the schema after the column name and type would allow the name and type to be parameters.
The constructor {anchorName HasCol}`here` can be used when the schema begins with the column {anchorTerm HasCol}`⟨name, t⟩`; it is thus a pointer to the first column in the schema that can only be used when the first column has the desired name and type.
The constructor {anchorName HasCol}`there` transforms a pointer into a smaller schema into a pointer into a schema with one more column on it.
Because {anchorTerm peak}`"elevation"` is the third column in {anchorName peak}`peak`, it can be found by looking past the first two columns with {anchorName HasCol}`there`, after which it is the first column.
In other words, to satisfy the type {anchorTerm peakElevationInt}`HasCol peak "elevation" .int`, use the expression {anchorTerm peakElevationInt}`.there (.there .here)`.
One way to think about {anchorName HasCol}`HasCol` is as a kind of decorated {anchorName Naturals}`Nat`—{anchorName Naturals}`zero` corresponds to {anchorName HasCol}`here`, and {anchorName Naturals}`succ` corresponds to {anchorName HasCol}`there`.
The extra type information makes it impossible to have off-by-one errors.
A pointer to a particular column in a schema can be used to extract that column's value from a row:
```anchor Rowget
def Row.get (row : Row s) (col : HasCol s n t) : t.asType :=
match s, col, row with
| [_], .here, v => v
| _::_::_, .here, (v, _) => v
| _::_::_, .there next, (_, r) => get r next
```
The first step is to pattern match on the schema, because this determines whether the row is a tuple or a single value.
No case is needed for the empty schema because there is a {anchorName HasCol}`HasCol` available, and both constructors of {anchorName HasCol}`HasCol` specify non-empty schemas.
If the schema has just a single column, then the pointer must point to it, so only the {anchorName HasCol}`here` constructor of {anchorName HasCol}`HasCol` need be matched.
If the schema has two or more columns, then there must be a case for {anchorName HasCol}`here`, in which case the value is the first one in the row, and one for {anchorName HasCol}`there`, in which case a recursive call is used.
Because the {anchorName HasCol}`HasCol` type guarantees that the column exists in the row, {anchorName Rowget}`Row.get` does not need to return an {anchorName nullable}`Option`.
{anchorName HasCol}`HasCol` plays two roles:
1. It serves as _evidence_ that a column with a particular name and type exists in a schema.
2. It serves as _data_ that can be used to find the value associated with the column in a row.
The first role, that of evidence, is similar to way that propositions are used.
The definition of the indexed family {anchorName HasCol}`HasCol` can be read as a specification of what counts as evidence that a given column exists.
Unlike propositions, however, it matters which constructor of {anchorName HasCol}`HasCol` was used.
In the second role, the constructors are used like {anchorName Naturals}`Nat`s to find data in a collection.
Programming with indexed families often requires the ability to switch fluently between both perspectives.
## Subschemas
%%%
tag := "subschemas"
%%%
One important operation in relational algebra is to _project_ a table or row into a smaller schema.
Every column not present in the smaller schema is forgotten.
In order for projection to make sense, the smaller schema must be a subschema of the larger schema, which means that every column in the smaller schema must be present in the larger schema.
Just as {anchorName HasCol}`HasCol` makes it possible to write a single-column lookup in a row that cannot fail, a representation of the subschema relationship as an indexed family makes it possible to write a projection function that cannot fail.
The ways in which one schema can be a subschema of another can be defined as an indexed family.
The basic idea is that a smaller schema is a subschema of a bigger schema if every column in the smaller schema occurs in the bigger schema.
If the smaller schema is empty, then it's certainly a subschema of the bigger schema, represented by the constructor {anchorName Subschema}`nil`.
If the smaller schema has a column, then that column must be in the bigger schema, and all the rest of the columns in the subschema must also be a subschema of the bigger schema.
This is represented by the constructor {anchorName Subschema}`cons`.
```anchor Subschema
inductive Subschema : Schema → Schema → Type where
| nil : Subschema [] bigger
| cons :
HasCol bigger n t →
Subschema smaller bigger →
Subschema (⟨n, t⟩ :: smaller) bigger
```
In other words, {anchorName Subschema}`Subschema` assigns each column of the smaller schema a {anchorName HasCol}`HasCol` that points to its location in the larger schema.
The schema {anchorName travelDiary}`travelDiary` represents the fields that are common to both {anchorName peak}`peak` and {anchorName waterfall}`waterfall`:
```anchor travelDiary
abbrev travelDiary : Schema :=
[⟨"name", .string⟩, ⟨"location", .string⟩, ⟨"lastVisited", .int⟩]
```
It is certainly a subschema of {anchorName peak}`peak`, as shown by this example:
```anchor peakDiarySub
example : Subschema travelDiary peak :=
.cons .here
(.cons (.there .here)
(.cons (.there (.there (.there .here))) .nil))
```
However, code like this is difficult to read and difficult to maintain.
One way to improve it is to instruct Lean to write the {anchorName Subschema}`Subschema` and {anchorName HasCol}`HasCol` constructors automatically.
This can be done using the tactic feature that was introduced in {ref "props-proofs-indexing"}[the Interlude on propositions and proofs].
That interlude uses {kw}`by decide` and {kw}`by simp` to provide evidence of various propositions.
In this context, two tactics are useful:
* The {kw}`constructor` tactic instructs Lean to solve the problem using the constructor of a datatype.
* The {kw}`repeat` tactic instructs Lean to repeat a tactic over and over until it either fails or the proof is finished.
In the next example, {kw}`by constructor` has the same effect as just writing {anchorName peakDiarySub}`.nil` would have:
```anchor emptySub
example : Subschema [] peak := by constructor
```
However, attempting that same tactic with a slightly more complicated type fails:
```anchor notDone
example : Subschema [⟨"location", .string⟩] peak := by constructor
```
```anchorError notDone
unsolved goals
case a
⊢ HasCol peak "location" DBType.string
case a
⊢ Subschema [] peak
```
Errors that begin with {lit}`unsolved goals` describe tactics that failed to completely build the expressions that they were supposed to.
In Lean's tactic language, a _goal_ is a type that a tactic is to fulfill by constructing an appropriate expression behind the scenes.
In this case, {kw}`constructor` caused {anchorName SubschemaNames}`Subschema.cons` to be applied, and the two goals represent the two arguments expected by {anchorName Subschema}`cons`.
Adding another instance of {kw}`constructor` causes the first goal ({anchorTerm SubschemaNames}`HasCol peak "location" DBType.string`) to be addressed with {anchorName SubschemaNames}`HasCol.there`, because {anchorName peak}`peak`'s first column is not {anchorTerm SubschemaNames}`"location"`:
```anchor notDone2
example : Subschema [⟨"location", .string⟩] peak := by
constructor
constructor
```
```anchorError notDone2
unsolved goals
case a.a
⊢ HasCol
[{ name := "location", contains := DBType.string }, { name := "elevation", contains := DBType.int },
{ name := "lastVisited", contains := DBType.int }]
"location" DBType.string
case a
⊢ Subschema [] peak
```
However, adding a third {kw}`constructor` results in the first goal being solved, because {anchorName SubschemaNames}`HasCol.here` is applicable:
```anchor notDone3
example : Subschema [⟨"location", .string⟩] peak := by
constructor
constructor
constructor
```
```anchorError notDone3
unsolved goals
case a
⊢ Subschema [] peak
```
A fourth instance of {kw}`constructor` solves the {anchorTerm SubschemaNames}`Subschema peak []` goal:
```anchor notDone4
example : Subschema [⟨"location", .string⟩] peak := by
constructor
constructor
constructor
constructor
```
Indeed, a version written without the use of tactics has four constructors:
```anchor notDone5
example : Subschema [⟨"location", .string⟩] peak :=
.cons (.there .here) .nil
```
Instead of experimenting to find the right number of times to write {kw}`constructor`, the {kw}`repeat` tactic can be used to ask Lean to just keep trying {kw}`constructor` as long as it keeps making progress:
```anchor notDone6
example : Subschema [⟨"location", .string⟩] peak := by repeat constructor
```
This more flexible version also works for more interesting {anchorName Subschema}`Subschema` problems:
```anchor subschemata
example : Subschema travelDiary peak := by repeat constructor
example : Subschema travelDiary waterfall := by repeat constructor
```
The approach of blindly trying constructors until something works is not very useful for types like {anchorName Naturals}`Nat` or {anchorTerm misc}`List Bool`.
Just because an expression has type {anchorName Naturals}`Nat` doesn't mean that it's the _correct_ {anchorName Naturals}`Nat`, after all.
But types like {anchorName HasCol}`HasCol` and {anchorName Subschema}`Subschema` are sufficiently constrained by their indices that only one constructor will ever be applicable, which means that the contents of the program itself are less interesting, and a computer can pick the correct one.
If one schema is a subschema of another, then it is also a subschema of the larger schema extended with an additional column.
This fact can be captured as a function definition.
{anchorName SubschemaAdd}`Subschema.addColumn` takes evidence that {anchorName SubschemaAdd}`smaller` is a subschema of {anchorName SubschemaAdd}`bigger`, and then returns evidence that {anchorName SubschemaAdd}`smaller` is a subschema of {anchorTerm SubschemaAdd}`c :: bigger`, that is, {anchorName SubschemaAdd}`bigger` with one additional column:
```anchor SubschemaAdd
def Subschema.addColumn :
Subschema smaller bigger →
Subschema smaller (c :: bigger)
| .nil => .nil
| .cons col sub' => .cons (.there col) sub'.addColumn
```
A subschema describes where to find each column from the smaller schema in the larger schema.
{anchorName SubschemaAdd}`Subschema.addColumn` must translate these descriptions from the original larger schema into the extended larger schema.
In the {anchorName Subschema}`nil` case, the smaller schema is {lit}`[]`, and {anchorName Subschema}`nil` is also evidence that {lit}`[]` is a subschema of {anchorTerm SubschemaAdd}`c :: bigger`.
In the {anchorName Subschema}`cons` case, which describes how to place one column from {anchorName SubschemaAdd}`smaller` into {anchorName SubschemaAdd}`bigger`, the placement of the column needs to be adjusted with {anchorName HasCol}`there` to account for the new column {anchorName SubschemaAdd}`c`, and a recursive call adjusts the rest of the columns.
Another way to think about {anchorName Subschema}`Subschema` is that it defines a _relation_ between two schemas—the existence of an expression with type {anchorTerm misc}`Subschema smaller bigger` means that {anchorTerm misc}`(smaller, bigger)` is in the relation.
This relation is reflexive, meaning that every schema is a subschema of itself:
```anchor SubschemaSame
def Subschema.reflexive : (s : Schema) → Subschema s s
| [] => .nil
| _ :: cs => .cons .here (reflexive cs).addColumn
```
## Projecting Rows
%%%
tag := "projecting-rows"
%%%
Given evidence that {anchorName RowProj}`s'` is a subschema of {anchorName RowProj}`s`, a row in {anchorName RowProj}`s` can be projected into a row in {anchorName RowProj}`s'`.
This is done using the evidence that {anchorName RowProj}`s'` is a subschema of {anchorName RowProj}`s`, which explains where each column of {anchorName RowProj}`s'` is found in {anchorName RowProj}`s`.
The new row in {anchorName RowProj}`s'` is built up one column at a time by retrieving the value from the appropriate place in the old row.
The function that performs this projection, {anchorName RowProj}`Row.project`, has three cases, one for each case of {anchorName RowProj}`Row` itself.
It uses {anchorName Rowget}`Row.get` together with each {anchorName HasCol}`HasCol` in the {anchorName RowProj}`Subschema` argument to construct the projected row:
```anchor RowProj
def Row.project (row : Row s) : (s' : Schema) → Subschema s' s → Row s'
| [], .nil => ()
| [_], .cons c .nil => row.get c
| _::_::_, .cons c cs => (row.get c, row.project _ cs)
```
# Conditions and Selection
%%%
tag := "conditions-and-selection"
%%%
Projection removes unwanted columns from a table, but queries must also be able to remove unwanted rows.
This operation is called _selection_.
Selection relies on having a means of expressing which rows are desired.
The example query language contains expressions, which are analogous to what can be written in a {lit}`WHERE` clause in SQL.
Expressions are represented by the indexed family {anchorName DBExpr}`DBExpr`.
Because expressions can refer to columns from the database, but different sub-expressions all have the same schema, {anchorName DBExpr}`DBExpr` takes the database schema as a parameter.
Additionally, each expression has a type, and these vary, making it an index:
```anchor DBExpr
inductive DBExpr (s : Schema) : DBType → Type where
| col (n : String) (loc : HasCol s n t) : DBExpr s t
| eq (e1 e2 : DBExpr s t) : DBExpr s .bool
| lt (e1 e2 : DBExpr s .int) : DBExpr s .bool
| and (e1 e2 : DBExpr s .bool) : DBExpr s .bool
| const : t.asType → DBExpr s t
```
The {anchorName DBExpr}`col` constructor represents a reference to a column in the database.
The {anchorName DBExpr}`eq` constructor compares two expressions for equality, {anchorName DBExpr}`lt` checks whether one is less than the other, {anchorName DBExpr}`and` is Boolean conjunction, and {anchorName DBExpr}`const` is a constant value of some type.
For example, an expression in {anchorName peak}`peak` that checks whether the {lit}`elevation` column is greater than 1000 and the location is {anchorTerm mountainDiary}`"Denmark"` can be written:
```anchor tallDk
def tallInDenmark : DBExpr peak .bool :=
.and (.lt (.const 1000) (.col "elevation" (by repeat constructor)))
(.eq (.col "location" (by repeat constructor)) (.const "Denmark"))
```
This is somewhat noisy.
In particular, references to columns contain boilerplate calls to {anchorTerm tallDk}`by repeat constructor`.
A Lean feature called _macros_ can help make expressions easier to read by eliminating this boilerplate:
```anchor cBang
macro "c!" n:term : term => `(DBExpr.col $n (by repeat constructor))
```
This declaration adds the {kw}`c!` keyword to Lean, and instructs Lean to replace any instance of {kw}`c!` followed by an expression with the corresponding {anchorTerm cBang}`DBExpr.col` construction.
Here, {anchorName cBang}`term` stands for Lean expressions, rather than commands, tactics, or some other part of the language.
Lean macros are a bit like C preprocessor macros, except they are better integrated into the language and they automatically avoid some of the pitfalls of CPP.
In fact, they are very closely related to macros in Scheme and Racket.
With this macro, the expression can be much easier to read:
```anchor tallDkBetter
def tallInDenmark : DBExpr peak .bool :=
.and (.lt (.const 1000) (c! "elevation"))
(.eq (c! "location") (.const "Denmark"))
```
Finding the value of an expression with respect to a given row uses {anchorName Rowget}`Row.get` to extract column references, and it delegates to Lean's operations on values for every other expression:
```anchor DBExprEval
def DBExpr.evaluate (row : Row s) : DBExpr s t → t.asType
| .col _ loc => row.get loc
| .eq e1 e2 => evaluate row e1 == evaluate row e2
| .lt e1 e2 => evaluate row e1 < evaluate row e2
| .and e1 e2 => evaluate row e1 && evaluate row e2
| .const v => v
```
Evaluating the expression for Valby Bakke, the tallest hill in the Copenhagen area, yields {anchorName misc}`false` because Valby Bakke is much less than 1 km over sea level:
```anchor valbybakke
#eval tallInDenmark.evaluate ("Valby Bakke", "Denmark", 31, 2023)
```
```anchorInfo valbybakke
false
```
Evaluating it for a fictional mountain of 1230m elevation yields {anchorName misc}`true`:
```anchor fakeDkBjerg
#eval tallInDenmark.evaluate ("Fictional mountain", "Denmark", 1230, 2023)
```
```anchorInfo fakeDkBjerg
true
```
Evaluating it for the highest peak in the US state of Idaho yields {anchorName misc}`false`, as Idaho is not part of Denmark:
```anchor borah
#eval tallInDenmark.evaluate ("Mount Borah", "USA", 3859, 1996)
```
```anchorInfo borah
false
```
# Queries
%%%
tag := "typed-query-language"
%%%
The query language is based on relational algebra.
In addition to tables, it includes the following operators:
1. The union of two expressions that have the same schema combines the rows that result from two queries
2. The difference of two expressions that have the same schema removes rows found in the second result from the rows in the first result
3. Selection by some criterion filters the result of a query according to an expression
4. Projection into a subschema, removing columns from the result of a query
5. Cartesian product, combining every row from one query with every row from another
6. Renaming a column in the result of a query, which modifies its schema
7. Prefixing all columns in a query with a name
The last operator is not strictly necessary, but it makes the language more convenient to use.
Once again, queries are represented by an indexed family:
```anchor Query
inductive Query : Schema → Type where
| table : Table s → Query s
| union : Query s → Query s → Query s
| diff : Query s → Query s → Query s
| select : Query s → DBExpr s .bool → Query s
| project :
Query s → (s' : Schema) →
Subschema s' s →
Query s'
| product :
Query s1 → Query s2 →
disjoint (s1.map Column.name) (s2.map Column.name) →
Query (s1 ++ s2)
| renameColumn :
Query s → (c : HasCol s n t) → (n' : String) →
!((s.map Column.name).contains n') →
Query (s.renameColumn c n')
| prefixWith :
(n : String) → Query s →
Query (s.map fun c => {c with name := n ++ "." ++ c.name})
```
The {anchorName Query}`select` constructor requires that the expression used for selection return a Boolean.
The {anchorName Query}`product` constructor's type contains a call to {anchorName Query}`disjoint`, which ensures that the two schemas don't share any names:
```anchor disjoint
def disjoint [BEq α] (xs ys : List α) : Bool :=
not (xs.any ys.contains || ys.any xs.contains)
```
The use of an expression of type {anchorName misc}`Bool` where a type is expected triggers a coercion from {anchorName misc}`Bool` to {anchorTerm misc}`Prop`.
Just as decidable propositions can be considered to be Booleans, where evidence for the proposition is coerced to {anchorName misc}`true` and refutations of the proposition are coerced to {anchorName misc}`false`, Booleans are coerced into the proposition that states that the expression is equal to {anchorName misc}`true`.
Because all uses of the library are expected to occur in contexts where the schemas are known ahead of time, this proposition can be proved with {kw}`by simp`.
Similarly, the {anchorName renameColumn}`renameColumn` constructor checks that the new name does not already exist in the schema.
It uses the helper {anchorName renameColumn}`Schema.renameColumn` to change the name of the column pointed to by {anchorName HasCol}`HasCol`:
```anchor renameColumn
def Schema.renameColumn : (s : Schema) → HasCol s n t → String → Schema
| c :: cs, .here, n' => {c with name := n'} :: cs
| c :: cs, .there next, n' => c :: renameColumn cs next n'
```
# Executing Queries
%%%
tag := "executing-queries"
%%%
Executing queries requires a number of helper functions.
The result of a query is a table; this means that each operation in the query language requires a corresponding implementation that works with tables.
## Cartesian Product
%%%
tag := "executing-cartesian-product"
%%%
Taking the Cartesian product of two tables is done by appending each row from the first table to each row from the second.
First off, due to the structure of {anchorName Row}`Row`, adding a single column to a row requires pattern matching on its schema in order to determine whether the result will be a bare value or a tuple.
Because this is a common operation, factoring the pattern matching out into a helper is convenient:
```anchor addVal
def addVal (v : c.contains.asType) (row : Row s) : Row (c :: s) :=
match s, row with
| [], () => v
| c' :: cs, v' => (v, v')
```
Appending two rows is recursive on the structure of both the first schema and the first row, because the structure of the row proceeds in lock-step with the structure of the schema.
When the first row is empty, appending returns the second row.
When the first row is a singleton, the value is added to the second row.
When the first row contains multiple columns, the first column's value is added to the result of recursion on the remainder of the row.
```anchor RowAppend
def Row.append (r1 : Row s1) (r2 : Row s2) : Row (s1 ++ s2) :=
match s1, r1 with
| [], () => r2
| [_], v => addVal v r2
| _::_::_, (v, r') => (v, r'.append r2)
```
{anchorName ListFlatMap}`List.flatMap`, found in the standard library, applies a function that itself returns a list to every entry in an input list, returning the result of appending the resulting lists in order:
```anchor ListFlatMap
def List.flatMap (f : α → List β) : (xs : List α) → List β
| [] => []
| x :: xs => f x ++ xs.flatMap f
```
The type signature suggests that {anchorName ListFlatMap}`List.flatMap` could be used to implement a {anchorTerm ListMonad}`Monad List` instance.
Indeed, together with {anchorTerm ListMonad}`pure x := [x]`, {anchorName ListFlatMap}`List.flatMap` does implement a monad.
However, it's not a very useful {anchorName ListMonad}`Monad` instance.
The {anchorName ListMonad}`List` monad is basically a version of {anchorName Many (module:=Examples.Monads.Many)}`Many` that explores _every_ possible path through the search space in advance, before users have the chance to request some number of values.
Because of this performance trap, it's usually not a good idea to define a {anchorName ListMonad}`Monad` instance for {anchorName ListMonad}`List`.
Here, however, the query language has no operator for restricting the number of results to be returned, so combining all possibilities is exactly what is desired:
```anchor TableCartProd
def Table.cartesianProduct (table1 : Table s1) (table2 : Table s2) :
Table (s1 ++ s2) :=
table1.flatMap fun r1 => table2.map r1.append
```
Just as with {anchorName ListProduct (module:=Examples.DependentTypes.Finite)}`List.product`, a loop with mutation in the identity monad can be used as an alternative implementation technique:
```anchor TableCartProdOther
def Table.cartesianProduct (table1 : Table s1) (table2 : Table s2) :
Table (s1 ++ s2) := Id.run do
let mut out : Table (s1 ++ s2) := []
for r1 in table1 do
for r2 in table2 do
out := (r1.append r2) :: out
pure out.reverse
```
## Difference
%%%
tag := "executing-difference"
%%%
Removing undesired rows from a table can be done using {anchorName misc}`List.filter`, which takes a list and a function that returns a {anchorName misc}`Bool`.
A new list is returned that contains only the entries for which the function returns {anchorName misc}`true`.
For instance,
```anchorTerm filterA
["Willamette", "Columbia", "Sandy", "Deschutes"].filter (·.length > 8)
```
evaluates to
```anchorTerm filterA
["Willamette", "Deschutes"]
```
because {anchorTerm filterA}`"Columbia"` and {anchorTerm filterA}`"Sandy"` have lengths less than or equal to {anchorTerm filterA}`8`.
Removing the entries of a table can be done using the helper {anchorName ListWithout}`List.without`:
```anchor ListWithout
def List.without [BEq α] (source banned : List α) : List α :=
source.filter fun r => !(banned.contains r)
```
This will be used with the {anchorName BEqDBType}`BEq` instance for {anchorName Row}`Row` when interpreting queries.
## Renaming Columns
%%%
tag := "executing-renaming-columns"
%%%
Renaming a column in a row is done with a recursive function that traverses the row until the column in question is found, at which point the column with the new name gets the same value as the column with the old name:
```anchor renameRow
def Row.rename (c : HasCol s n t) (row : Row s) :
Row (s.renameColumn c n') :=
match s, row, c with
| [_], v, .here => v
| _::_::_, (v, r), .here => (v, r)
| _::_::_, (v, r), .there next => addVal v (r.rename next)
```
While this function changes the _type_ of its argument, the actual return value contains precisely the same data as the original argument.
From a run-time perspective, {anchorName renameRow}`Row.rename` is nothing but a slow identity function.
One difficulty in programming with indexed families is that when performance matters, this kind of operation can get in the way.
It takes a very careful, often brittle, design to eliminate these kinds of “re-indexing” functions.
## Prefixing Column Names
%%%
tag := "executing-prefixing-column-names"
%%%
Adding a prefix to column names is very similar to renaming a column.
Instead of proceeding to a desired column and then returning, {anchorName prefixRow}`prefixRow` must process all columns:
```anchor prefixRow
def prefixRow (row : Row s) :
Row (s.map fun c => {c with name := n ++ "." ++ c.name}) :=
match s, row with
| [], _ => ()
| [_], v => v
| _::_::_, (v, r) => (v, prefixRow r)
```
This can be used with {anchorName misc}`List.map` in order to add a prefix to all rows in a table.
Once again, this function only exists to change the type of a value.
## Putting the Pieces Together
%%%
tag := "query-exec-runner"
%%%
With all of these helpers defined, executing a query requires only a short recursive function:
```anchor QueryExec
def Query.exec : Query s → Table s
| .table t => t
| .union q1 q2 => exec q1 ++ exec q2
| .diff q1 q2 => exec q1 |>.without (exec q2)
| .select q e => exec q |>.filter e.evaluate
| .project q _ sub => exec q |>.map (·.project _ sub)
| .product q1 q2 _ => exec q1 |>.cartesianProduct (exec q2)
| .renameColumn q c _ _ => exec q |>.map (·.rename c)
| .prefixWith _ q => exec q |>.map prefixRow
```
Some arguments to the constructors are not used during execution.
In particular, both the constructor {anchorName Query}`project` and the function {anchorName RowProj}`Row.project` take the smaller schema as explicit arguments, but the type of the _evidence_ that this schema is a subschema of the larger schema contains enough information for Lean to fill out the argument automatically.
Similarly, the fact that the two tables have disjoint column names that is required by the {anchorName Query}`product` constructor is not needed by {anchorName TableCartProd}`Table.cartesianProduct`.
Generally speaking, dependent types provide many opportunities to have Lean fill out arguments on behalf of the programmer.
Dot notation is used with the results of queries to call functions defined both in the {lit}`Table` and {lit}`List` namespaces, such {anchorName misc}`List.map`, {anchorName misc}`List.filter`, and {anchorName TableCartProd}`Table.cartesianProduct`.
This works because {anchorName Table}`Table` is defined using {kw}`abbrev`.
Just like type class search, dot notation can see through definitions created with {kw}`abbrev`.
The implementation of {anchorName Query}`select` is also quite concise.
After executing the query {anchorName selectCase}`q`, {anchorName misc}`List.filter` is used to remove the rows that do not satisfy the expression.
{anchorName misc}`List.filter` expects a function from {anchorTerm Table}`Row s` to {anchorName misc}`Bool`, but {anchorName DBExprEval}`DBExpr.evaluate` has type {anchorTerm DBExprEvalType}`Row s → DBExpr s t → t.asType`.
Because the type of the {anchorName Query}`select` constructor requires that the expression have type {anchorTerm Query}`DBExpr s .bool`, {anchorTerm DBExprEvalType}`t.asType` is actually {anchorName misc}`Bool` in this context.
A query that finds the heights of all mountain peaks with an elevation greater than 500 meters can be written:
```anchor Query1
open Query in
def example1 :=
table mountainDiary |>.select
(.lt (.const 500) (c! "elevation")) |>.project
[⟨"elevation", .int⟩] (by repeat constructor)
```
Executing it returns the expected list of integers:
```anchor Query1Exec
#eval example1.exec
```
```anchorInfo Query1Exec
[3637, 1519, 2549]
```
To plan a sightseeing tour, it may be relevant to match all pairs mountains and waterfalls in the same location.
This can be done by taking the Cartesian product of both tables, selecting only the rows in which they are equal, and then projecting out the names:
```anchor Query2
open Query in
def example2 :=
let mountain := table mountainDiary |>.prefixWith "mountain"
let waterfall := table waterfallDiary |>.prefixWith "waterfall"
mountain.product waterfall (by decide)
|>.select (.eq (c! "mountain.location") (c! "waterfall.location"))
|>.project [⟨"mountain.name", .string⟩, ⟨"waterfall.name", .string⟩]
(by repeat constructor)
```
Because the example data includes only waterfalls in the USA, executing the query returns pairs of mountains and waterfalls in the US:
```anchor Query2Exec
#eval example2.exec
```
```anchorInfo Query2Exec
[("Mount Nebo", "Multnomah Falls"), ("Mount Nebo", "Shoshone Falls"), ("Moscow Mountain", "Multnomah Falls"),
("Moscow Mountain", "Shoshone Falls"), ("Mount St. Helens", "Multnomah Falls"),
("Mount St. Helens", "Shoshone Falls")]
```
## Errors You May Meet
%%%
tag := "typed-queries-error-messages"
%%%
Many potential errors are ruled out by the definition of {anchorName Query}`Query`.
For instance, forgetting the added qualifier in {anchorTerm Query2}`"mountain.location"` yields a compile-time error that highlights the column reference {anchorTerm QueryOops1}`c! "location"`:
```anchor QueryOops1
open Query in
def example2 :=
let mountains := table mountainDiary |>.prefixWith "mountain"
let waterfalls := table waterfallDiary |>.prefixWith "waterfall"
mountains.product waterfalls (by simp)
|>.select (.eq (c! "location") (c! "waterfall.location"))
|>.project [⟨"mountain.name", .string⟩, ⟨"waterfall.name", .string⟩]
(by repeat constructor)
```
This is excellent feedback!
On the other hand, the text of the error message is quite difficult to act on:
```anchorError QueryOops1
unsolved goals
case a.a.a.a.a.a.a
mountains : Query (List.map (fun c => { name := "mountain" ++ "." ++ c.name, contains := c.contains }) peak) := ⋯
waterfalls : Query (List.map (fun c => { name := "waterfall" ++ "." ++ c.name, contains := c.contains }) waterfall) := ⋯
⊢ HasCol (List.map (fun c => { name := "waterfall" ++ "." ++ c.name, contains := c.contains }) []) "location" ?m.62066
```
Similarly, forgetting to add prefixes to the names of the two tables results in an error on {kw}`by decide`, which should provide evidence that the schemas are in fact disjoint:
```anchor QueryOops2
open Query in
def example2 :=
let mountains := table mountainDiary
let waterfalls := table waterfallDiary
mountains.product waterfalls (by decide)
|>.select (.eq (c! "mountain.location") (c! "waterfall.location"))
|>.project [⟨"mountain.name", .string⟩, ⟨"waterfall.name", .string⟩]
(by repeat constructor)
```
This error message is more helpful:
```anchorError QueryOops2
Tactic `decide` proved that the proposition
disjoint (List.map Column.name peak) (List.map Column.name waterfall) = true
is false
```
Lean's macro system contains everything needed not only to provide a convenient syntax for queries, but also to arrange for the error messages to be helpful.
Unfortunately, it is beyond the scope of this book to provide a description of implementing languages with Lean macros.
An indexed family such as {anchorName Query}`Query` is probably best as the core of a typed database interaction library, rather than its user interface.
# Exercises
%%%
tag := "typed-query-exercises"
%%%
## Dates
%%%
tag := none
%%%
Define a structure to represent dates. Add it to the {anchorName DBExpr}`DBType` universe and update the rest of the code accordingly. Provide the extra {anchorName DBExpr}`DBExpr` constructors that seem to be necessary.
## Nullable Types
%%%
tag := none
%%%
Add support for nullable columns to the query language by representing database types with the following structure:
```anchor nullable
structure NDBType where
underlying : DBType
nullable : Bool
abbrev NDBType.asType (t : NDBType) : Type :=
if t.nullable then
Option t.underlying.asType
else
t.underlying.asType
```
Use this type in place of {anchorName DBExpr}`DBType` in {anchorName Schema}`Column` and {anchorName DBExpr}`DBExpr`, and look up SQL's rules for {lit}`NULL` and comparison operators to determine the types of {anchorName DBExpr}`DBExpr`'s constructors.
## Experimenting with Tactics
%%%
tag := none
%%%
What is the result of asking Lean to find values of the following types using {kw}`by repeat constructor`? Explain why each gives the result that it does.
* {anchorName Naturals}`Nat`
* {anchorTerm misc}`List Nat`
* {anchorTerm misc}`Vect Nat 4`
* {anchorTerm misc}`Row []`
* {anchorTerm misc}`Row [⟨"price", .int⟩]`
* {anchorTerm misc}`Row peak`
* {anchorTerm misc}`HasCol [⟨"price", .int⟩, ⟨"price", .int⟩] "price" .int` |
fp-lean/book/FPLean/DependentTypes/IndexedFamilies.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.DependentTypes"
#doc (Manual) "Indexed Families" =>
%%%
tag := "indexed-families"
%%%
Polymorphic inductive types take type arguments.
For instance, {moduleName}`List` takes an argument that determines the type of the entries in the list, and {moduleName}`Except` takes arguments that determine the types of the exceptions or values.
These type arguments, which are the same in every constructor of the datatype, are referred to as _parameters_.
Arguments to inductive types need not be the same in every constructor, however.
Inductive types in which the arguments to the type vary based on the choice of constructor are called _indexed families_, and the arguments that vary are referred to as _indices_.
The “hello world” of indexed families is a type of lists that contains the length of the list in addition to the type of entries, conventionally referred to as “vectors”:
```anchor Vect
inductive Vect (α : Type u) : Nat → Type u where
| nil : Vect α 0
| cons : α → Vect α n → Vect α (n + 1)
```
The type of a vector of three {anchorName vect3}`String`s includes the fact that it contains three {anchorName vect3}`String`s:
```anchor vect3
example : Vect String 3 :=
.cons "one" (.cons "two" (.cons "three" .nil))
```
Function declarations may take some arguments before the colon, indicating that they are available in the entire definition, and some arguments after, indicating a desire to pattern-match on them and define the function case by case.
Inductive datatypes have a similar principle: the argument {anchorName Vect}`α` is named at the top of the datatype declaration, prior to the colon, which indicates that it is a parameter that must be provided as the first argument in all occurrences of {anchorName Vect}`Vect` in the definition, while the {anchorName Vect}`Nat` argument occurs after the colon, indicating that it is an index that may vary.
Indeed, the three occurrences of {anchorName Vect}`Vect` in the {anchorName Vect}`nil` and {anchorName Vect}`cons` constructor declarations consistently provide {anchorName Vect}`α` as the first argument, while the second argument is different in each case.
The declaration of {anchorName Vect}`nil` states that it is a constructor of type {anchorTerm Vect}`Vect α 0`.
This means that using {anchorName nilNotLengthThree}`Vect.nil` in a context expecting a {anchorTerm nilNotLengthThree}`Vect String 3` is a type error, just as {anchorTerm otherEx}`[1, 2, 3]` is a type error in a context that expects a {anchorTerm otherEx}`List String`:
```anchor nilNotLengthThree
example : Vect String 3 := Vect.nil
```
```anchorError nilNotLengthThree
Type mismatch
Vect.nil
has type
Vect ?m.3 0
but is expected to have type
Vect String 3
```
The mismatch between {anchorTerm Vect}`0` and {anchorTerm nilNotLengthThree}`3` in this example plays exactly the same role as any other type mismatch, even though {anchorTerm Vect}`0` and {anchorTerm nilNotLengthThree}`3` are not themselves types.
The metavariable in the message can be ignored because its presence indicates that {anchorName otherEx}`Vect.nil` can have any element type.
Indexed families are called _families_ of types because different index values can make different constructors available for use.
In some sense, an indexed family is not a type; rather, it is a collection of related types, and the choice of index values also chooses a type from the collection.
Choosing the index {anchorTerm otherEx}`5` for {anchorName Vect}`Vect` means that only the constructor {anchorName Vect}`cons` is available, and choosing the index {anchorTerm Vect}`0` means that only {anchorName Vect}`nil` is available.
If the index is not yet known (e.g. because it is a variable), then no constructor can be used until it becomes known.
Using {anchorName nilNotLengthN}`n` for the length allows neither {anchorName otherEx}`Vect.nil` nor {anchorName consNotLengthN}`Vect.cons`, because there's no way to know whether the variable {anchorName nilNotLengthN}`n` should stand for a {anchorName Vect}`Nat` that matches {anchorTerm Vect}`0` or {anchorTerm Vect}`n + 1`:
```anchor nilNotLengthN
example : Vect String n := Vect.nil
```
```anchorError nilNotLengthN
Type mismatch
Vect.nil
has type
Vect ?m.2 0
but is expected to have type
Vect String n
```
```anchor consNotLengthN
example : Vect String n := Vect.cons "Hello" (Vect.cons "world" Vect.nil)
```
```anchorError consNotLengthN
Type mismatch
Vect.cons "Hello" (Vect.cons "world" Vect.nil)
has type
Vect String (0 + 1 + 1)
but is expected to have type
Vect String n
```
Having the length of the list as part of its type means that the type becomes more informative.
For example, {anchorName replicateStart}`Vect.replicate` is a function that creates a {anchorName replicateStart}`Vect` with a number of copies of a given value.
The type that says this precisely is:
```anchor replicateStart
def Vect.replicate (n : Nat) (x : α) : Vect α n := _
```
The argument {anchorName replicateStart}`n` appears as the length of the result.
The message associated with the underscore placeholder describes the task at hand:
```anchorError replicateStart
don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
⊢ Vect α n
```
When working with indexed families, constructors can only be applied when Lean can see that the constructor's index matches the index in the expected type.
However, neither constructor has an index that matches {anchorName replicateStart}`n`—{anchorName Vect}`nil` matches {anchorName otherEx}`Nat.zero`, and {anchorName Vect}`cons` matches {anchorName otherEx}`Nat.succ`.
Just as in the example type errors, the variable {anchorName Vect}`n` could stand for either, depending on which {anchorName Vect}`Nat` is provided to the function as an argument.
The solution is to use pattern matching to consider both of the possible cases:
```anchor replicateMatchOne
def Vect.replicate (n : Nat) (x : α) : Vect α n :=
match n with
| 0 => _
| k + 1 => _
```
Because {anchorName replicateStart}`n` occurs in the expected type, pattern matching on {anchorName replicateStart}`n` _refines_ the expected type in the two cases of the match.
In the first underscore, the expected type has become {lit}`Vect α 0`:
```anchorError replicateMatchOne
don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
⊢ Vect α 0
```
In the second underscore, it has become {lit}`Vect α (k + 1)`:
```anchorError replicateMatchTwo
don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
k : Nat
⊢ Vect α (k + 1)
```
When pattern matching refines the type of a program in addition to discovering the structure of a value, it is called _dependent pattern matching_.
The refined type makes it possible to apply the constructors.
The first underscore matches {anchorName otherEx}`Vect.nil`, and the second matches {anchorName consNotLengthN}`Vect.cons`:
```anchor replicateMatchFour
def Vect.replicate (n : Nat) (x : α) : Vect α n :=
match n with
| 0 => .nil
| k + 1 => .cons _ _
```
The first underscore under the {anchorName replicateMatchFour}`.cons` should have type {anchorName replicateMatchFour}`α`.
There is an {anchorName replicateMatchFour}`α` available, namely {anchorName replicateMatchFour}`x`:
```anchorError replicateMatchFour
don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
k : Nat
⊢ α
```
The second underscore should be a {lit}`Vect α k`, which can be produced by a recursive call to {anchorName replicate}`replicate`:
```anchorError replicateMatchFive
don't know how to synthesize placeholder
context:
α : Type u_1
n : Nat
x : α
k : Nat
⊢ Vect α k
```
Here is the final definition of {anchorName replicate}`replicate`:
```anchor replicate
def Vect.replicate (n : Nat) (x : α) : Vect α n :=
match n with
| 0 => .nil
| k + 1 => .cons x (replicate k x)
```
In addition to providing assistance while writing the function, the informative type of {anchorName replicate}`Vect.replicate` also allows client code to rule out a number of unexpected functions without having to read the source code.
A version of {anchorName listReplicate}`replicate` for lists could produce a list of the wrong length:
```anchor listReplicate
def List.replicate (n : Nat) (x : α) : List α :=
match n with
| 0 => []
| k + 1 => x :: x :: replicate k x
```
However, making this mistake with {anchorName replicateOops}`Vect.replicate` is a type error:
```anchor replicateOops
def Vect.replicate (n : Nat) (x : α) : Vect α n :=
match n with
| 0 => .nil
| k + 1 => .cons x (.cons x (replicate k x))
```
```anchorError replicateOops
Application type mismatch: The argument
cons x (replicate k x)
has type
Vect α (k + 1)
but is expected to have type
Vect α k
in the application
cons x (cons x (replicate k x))
```
The function {anchorName otherEx}`List.zip` combines two lists by pairing the first entry in the first list with the first entry in the second list, the second entry in the first list with the second entry in the second list, and so forth.
{anchorName otherEx}`List.zip` can be used to pair the three highest peaks in the US state of Oregon with the three highest peaks in Denmark:
```anchorTerm zip1
["Mount Hood",
"Mount Jefferson",
"South Sister"].zip ["Møllehøj", "Yding Skovhøj", "Ejer Bavnehøj"]
```
The result is a list of three pairs:
```anchorTerm zip1
[("Mount Hood", "Møllehøj"),
("Mount Jefferson", "Yding Skovhøj"),
("South Sister", "Ejer Bavnehøj")]
```
It's somewhat unclear what should happen when the lists have different lengths.
Like many languages, Lean chooses to ignore the extra entries in one of the lists.
For instance, combining the heights of the five highest peaks in Oregon with those of the three highest peaks in Denmark yields three pairs.
In particular,
```anchorTerm zip2
[3428.8, 3201, 3158.5, 3075, 3064].zip [170.86, 170.77, 170.35]
```
evaluates to
```anchorTerm zip2
[(3428.8, 170.86), (3201, 170.77), (3158.5, 170.35)]
```
While this approach is convenient because it always returns an answer, it runs the risk of throwing away data when the lists unintentionally have different lengths.
F# takes a different approach: its version of {fsharp}`List.zip` throws an exception when the lengths don't match, as can be seen in this {lit}`fsi` session:
```fsharp
> List.zip [3428.8; 3201.0; 3158.5; 3075.0; 3064.0] [170.86; 170.77; 170.35];;
```
```fsharpError
System.ArgumentException: The lists had different lengths.
list2 is 2 elements shorter than list1 (Parameter 'list2')
at Microsoft.FSharp.Core.DetailedExceptions.invalidArgDifferentListLength[?](String arg1, String arg2, Int32 diff) in /builddir/build/BUILD/dotnet-v3.1.424-SDK/src/fsharp.3ef6f0b514198c0bfa6c2c09fefe41a740b024d5/src/fsharp/FSharp.Core/local.fs:line 24
at Microsoft.FSharp.Primitives.Basics.List.zipToFreshConsTail[a,b](FSharpList`1 cons, FSharpList`1 xs1, FSharpList`1 xs2) in /builddir/build/BUILD/dotnet-v3.1.424-SDK/src/fsharp.3ef6f0b514198c0bfa6c2c09fefe41a740b024d5/src/fsharp/FSharp.Core/local.fs:line 918
at Microsoft.FSharp.Primitives.Basics.List.zip[T1,T2](FSharpList`1 xs1, FSharpList`1 xs2) in /builddir/build/BUILD/dotnet-v3.1.424-SDK/src/fsharp.3ef6f0b514198c0bfa6c2c09fefe41a740b024d5/src/fsharp/FSharp.Core/local.fs:line 929
at Microsoft.FSharp.Collections.ListModule.Zip[T1,T2](FSharpList`1 list1, FSharpList`1 list2) in /builddir/build/BUILD/dotnet-v3.1.424-SDK/src/fsharp.3ef6f0b514198c0bfa6c2c09fefe41a740b024d5/src/fsharp/FSharp.Core/list.fs:line 466
at <StartupCode$FSI_0006>.$FSI_0006.main@()
Stopped due to error
```
This avoids accidentally discarding information, but crashing a program comes with its own difficulties.
The Lean equivalent, which would use the {anchorName otherEx}`Option` or {anchorName otherEx}`Except` monads, would introduce a burden that may not be worth the safety.
:::paragraph
Using {anchorName Vect}`Vect`, however, it is possible to write a version of {anchorName VectZip}`zip` with a type that requires that both arguments have the same length:
```anchor VectZip
def Vect.zip : Vect α n → Vect β n → Vect (α × β) n
| .nil, .nil => .nil
| .cons x xs, .cons y ys => .cons (x, y) (zip xs ys)
```
This definition only has patterns for the cases where either both arguments are {anchorName otherEx}`Vect.nil` or both arguments are {anchorName consNotLengthN}`Vect.cons`, and Lean accepts the definition without a “missing cases” error like the one that results from a similar definition for {anchorName otherEx}`List`:
```anchor zipMissing
def List.zip : List α → List β → List (α × β)
| [], [] => []
| x :: xs, y :: ys => (x, y) :: zip xs ys
```
```anchorError zipMissing
Missing cases:
(List.cons _ _), []
[], (List.cons _ _)
```
:::
This is because the constructor used in the first pattern, {anchorName Vect}`nil` or {anchorName Vect}`cons`, _refines_ the type checker's knowledge about the length {anchorName VectZip}`n`.
When the first pattern is {anchorName Vect}`nil`, the type checker can additionally determine that the length was {anchorTerm VectZipLen}`0`, so the only possible choice for the second pattern is {anchorName Vect}`nil`.
Similarly, when the first pattern is {anchorName Vect}`cons`, the type checker can determine that the length was {anchorTerm VectZipLen}`k+1` for some {anchorName VectZipLen}`Nat` {anchorName VectZipLen}`k`, so the only possible choice for the second pattern is {anchorName Vect}`cons`.
Indeed, adding a case that uses {anchorName Vect}`nil` and {anchorName Vect}`cons` together is a type error, because the lengths don't match:
```anchor zipExtraCons
def Vect.zip : Vect α n → Vect β n → Vect (α × β) n
| .nil, .nil => .nil
| .nil, .cons y ys => .nil
| .cons x xs, .cons y ys => .cons (x, y) (zip xs ys)
```
```anchorError zipExtraCons
Type mismatch
Vect.cons y ys
has type
Vect ?m.10 (?m.16 + 1)
but is expected to have type
Vect β 0
```
The refinement of the length can be observed by making {anchorName VectZipLen}`n` into an explicit argument:
```anchor VectZipLen
def Vect.zip : (n : Nat) → Vect α n → Vect β n → Vect (α × β) n
| 0, .nil, .nil => .nil
| k + 1, .cons x xs, .cons y ys => .cons (x, y) (zip k xs ys)
```
# Exercises
%%%
tag := "indexed-families-exercises"
%%%
Getting a feel for programming with dependent types requires experience, and the exercises in this section are very important.
For each exercise, try to see which mistakes the type checker can catch, and which ones it can't, by experimenting with the code as you go.
This is also a good way to develop a feel for the error messages.
* Double-check that {anchorName VectZip}`Vect.zip` gives the right answer when combining the three highest peaks in Oregon with the three highest peaks in Denmark.
Because {anchorName Vect}`Vect` doesn't have the syntactic sugar that {anchorName otherEx}`List` has, it can be helpful to begin by defining {anchorTerm exerciseDefs}`oregonianPeaks : Vect String 3` and {anchorTerm exerciseDefs}`danishPeaks : Vect String 3`.
* Define a function {anchorName exerciseDefs}`Vect.map` with type {anchorTerm exerciseDefs}`(α → β) → Vect α n → Vect β n`.
* Define a function {anchorName exerciseDefs}`Vect.zipWith` that combines the entries in a {anchorName Vect}`Vect` one at a time with a function.
It should have the type {anchorTerm exerciseDefs}`(α → β → γ) → Vect α n → Vect β n → Vect γ n`.
* Define a function {anchorName exerciseDefs}`Vect.unzip` that splits a {anchorName Vect}`Vect` of pairs into a pair of {anchorName Vect}`Vect`s. It should have the type {anchorTerm exerciseDefs}`Vect (α × β) n → Vect α n × Vect β n`.
* Define a function {anchorName exerciseDefs}`Vect.push` that adds an entry to the _end_ of a {anchorName Vect}`Vect`. Its type should be {anchorTerm exerciseDefs}`Vect α n → α → Vect α (n + 1)` and {anchorTerm snocSnowy}`#eval Vect.push (.cons "snowy" .nil) "peaks"` should yield {anchorInfo snocSnowy}`Vect.cons "snowy" (Vect.cons "peaks" (Vect.nil))`.
* Define a function {anchorName exerciseDefs}`Vect.reverse` that reverses the order of a {anchorName Vect}`Vect`.
* Define a function {anchorName exerciseDefs}`Vect.drop` with the following type: {anchorTerm exerciseDefs}`(n : Nat) → Vect α (k + n) → Vect α k`.
Verify that it works by checking that {anchorTerm ejerBavnehoej}`#eval danishPeaks.drop 2` yields {anchorInfo ejerBavnehoej}`Vect.cons "Ejer Bavnehøj" (Vect.nil)`.
* Define a function {anchorName take}`Vect.take` with type {anchorTerm take}`(n : Nat) → Vect α (k + n) → Vect α n` that returns the first {anchorName take}`n` entries in the {anchorName Vect}`Vect`. Check that it works on an example. |
fp-lean/book/FPLean/DependentTypes/UniversePattern.lean | import VersoManual
import FPLean.Examples
open Verso.Genre Manual
open Verso.Code.External
open FPLean
set_option verso.exampleProject "../examples"
set_option verso.exampleModule "Examples.DependentTypes.Finite"
#doc (Manual) "The Universe Design Pattern" =>
%%%
tag := "universe-pattern"
%%%
In Lean, types such as {anchorTerm sundries}`Type`, {anchorTerm sundries}`Type 3`, and {anchorTerm sundries}`Prop` that classify other types are known as universes.
However, the term _universe_ is also used for a design pattern in which a datatype is used to represent a subset of Lean's types, and a function converts the datatype's constructors into actual types.
The values of this datatype are called _codes_ for their types.
Just like Lean's built-in universes, the universes implemented with this pattern are types that describe some collection of available types, even though the mechanism by which it is done is different.
In Lean, there are types such as {anchorTerm sundries}`Type`, {anchorTerm sundries}`Type 3`, and {anchorTerm sundries}`Prop` that directly describe other types.
This arrangement is referred to as {deftech}_universes à la Russell_.
The user-defined universes described in this section represent all of their types as _data_, and include an explicit function to interpret these codes into actual honest-to-goodness types.
This arrangement is referred to as {deftech}_universes à la Tarski_.
While languages such as Lean that are based on dependent type theory almost always use Russell-style universes, Tarski-style universes are a useful pattern for defining APIs in these languages.
Defining a custom universe makes it possible to carve out a closed collection of types that can be used with an API.
Because the collection of types is closed, recursion over the codes allows programs to work for _any_ type in the universe.
One example of a custom universe has the codes {anchorName NatOrBool}`nat`, standing for {anchorName NatOrBool}`Nat`, and {anchorName NatOrBool}`bool`, standing for {anchorName NatOrBool}`Bool`:
```anchor NatOrBool
inductive NatOrBool where
| nat | bool
abbrev NatOrBool.asType (code : NatOrBool) : Type :=
match code with
| .nat => Nat
| .bool => Bool
```
Pattern matching on a code allows the type to be refined, just as pattern matching on the constructors of {moduleName (module := Examples.DependentTypes)}`Vect` allows the expected length to be refined.
For instance, a program that deserializes the types in this universe from a string can be written as follows:
```anchor decode
def decode (t : NatOrBool) (input : String) : Option t.asType :=
match t with
| .nat => input.toNat?
| .bool =>
match input with
| "true" => some true
| "false" => some false
| _ => none
```
Dependent pattern matching on {anchorName decode}`t` allows the expected result type {anchorTerm decode}`t.asType` to be respectively refined to {anchorTerm natOrBoolExamples}`NatOrBool.nat.asType` and {anchorTerm natOrBoolExamples}`NatOrBool.bool.asType`, and these compute to the actual types {anchorName NatOrBool}`Nat` and {anchorName NatOrBool}`Bool`.
Like any other data, codes may be recursive.
The type {anchorName NestedPairs}`NestedPairs` codes for any possible nesting of the pair and natural number types:
```anchor NestedPairs
inductive NestedPairs where
| nat : NestedPairs
| pair : NestedPairs → NestedPairs → NestedPairs
abbrev NestedPairs.asType : NestedPairs → Type
| .nat => Nat
| .pair t1 t2 => asType t1 × asType t2
```
In this case, the interpretation function {anchorName NestedPairs}`NestedPairs.asType` is recursive.
This means that recursion over codes is required in order to implement {anchorName NestedPairsbeq}`BEq` for the universe:
```anchor NestedPairsbeq
def NestedPairs.beq (t : NestedPairs) (x y : t.asType) : Bool :=
match t with
| .nat => x == y
| .pair t1 t2 => beq t1 x.fst y.fst && beq t2 x.snd y.snd
instance {t : NestedPairs} : BEq t.asType where
beq x y := t.beq x y
```
Even though every type in the {anchorName beqNoCases}`NestedPairs` universe already has a {anchorName beqNoCases}`BEq` instance, type class search does not automatically check every possible case of a datatype in an instance declaration, because there might be infinitely many such cases, as with {anchorName beqNoCases}`NestedPairs`.
Attempting to appeal directly to the {anchorName beqNoCases}`BEq` instances rather than explaining to Lean how to find them by recursion on the codes results in an error:
```anchor beqNoCases
instance {t : NestedPairs} : BEq t.asType where
beq x y := x == y
```
```anchorError beqNoCases
failed to synthesize
BEq t.asType
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
```
The {anchorName beqNoCases}`t` in the error message stands for an unknown value of type {anchorName beqNoCases}`NestedPairs`.
# Type Classes vs Universes
%%%
tag := "type-classes-vs-universe-pattern"
%%%
Type classes allow an open-ended collection of types to be used with an API as long as they have implementations of the necessary interfaces.
In most cases, this is preferable.
It is hard to predict all use cases for an API ahead of time, and type classes are a convenient way to allow library code to be used with more types than the original author expected.
A universe à la Tarski, on the other hand, restricts the API to be usable only with a predetermined collection of types.
This is useful in a few situations:
* When a function should act very differently depending on which type it is passed—it is impossible to pattern match on types themselves, but pattern matching on codes for types is allowed
* When an external system inherently limits the types of data that may be provided, and extra flexibility is not desired
* When additional properties of a type are required over and above the implementation of some operations
Type classes are useful in many of the same situations as interfaces in Java or C#, while a universe à la Tarski can be useful in cases where a sealed class might be used, but where an ordinary inductive datatype is not usable.
# A Universe of Finite Types
%%%
tag := "finite-type-universe"
%%%
Restricting the types that can be used with an API to a predetermined collection can enable operations that would be impossible for an open-ended API.
For example, functions can't normally be compared for equality.
Functions should be considered equal when they map the same inputs to the same outputs.
Checking this could take infinite amounts of time, because comparing two functions with type {anchorTerm sundries}`Nat → Bool` would require checking that the functions returned the same {anchorName sundries}`Bool` for each and every {anchorName sundries}`Nat`.
In other words, a function from an infinite type is itself infinite.
Functions can be viewed as tables, and a function whose argument type is infinite requires infinitely many rows to represent each case.
But functions from finite types require only finitely many rows in their tables, making them finite.
Two functions whose argument type is finite can be checked for equality by enumerating all possible arguments, calling the functions on each of them, and then comparing the results.
Checking higher-order functions for equality requires generating all possible functions of a given type, which additionally requires that the return type is finite so that each element of the argument type can be mapped to each element of the return type.
This is not a _fast_ method, but it does complete in finite time.
One way to represent finite types is by a universe:
```anchor Finite
inductive Finite where
| unit : Finite
| bool : Finite
| pair : Finite → Finite → Finite
| arr : Finite → Finite → Finite
abbrev Finite.asType : Finite → Type
| .unit => Unit
| .bool => Bool
| .pair t1 t2 => asType t1 × asType t2
| .arr dom cod => asType dom → asType cod
```
In this universe, the constructor {anchorName Finite}`arr` stands for the function type, which is written with an {anchorName Finite}`arr`ow.
:::paragraph
Comparing two values from this universe for equality is almost the same as in the {anchorName NestedPairs}`NestedPairs` universe.
The only important difference is the addition of the case for {anchorName Finite}`arr`, which uses a helper called {anchorName FiniteAll}`Finite.enumerate` to generate every value from the type coded for by {anchorName FiniteBeq}`dom`, checking that the two functions return equal results for every possible input:
```anchor FiniteBeq
def Finite.beq (t : Finite) (x y : t.asType) : Bool :=
match t with
| .unit => true
| .bool => x == y
| .pair t1 t2 => beq t1 x.fst y.fst && beq t2 x.snd y.snd
| .arr dom cod =>
dom.enumerate.all fun arg => beq cod (x arg) (y arg)
```
The standard library function {anchorName sundries}`List.all` checks that the provided function returns {anchorName sundries}`true` on every entry of a list.
This function can be used to compare functions on the Booleans for equality:
```anchor arrBoolBoolEq
#eval Finite.beq (.arr .bool .bool) (fun _ => true) (fun b => b == b)
```
```anchorInfo arrBoolBoolEq
true
```
It can also be used to compare functions from the standard library:
```anchor arrBoolBoolEq2
#eval Finite.beq (.arr .bool .bool) (fun _ => true) not
```
```anchorInfo arrBoolBoolEq2
false
```
It can even compare functions built using tools such as function composition:
```anchor arrBoolBoolEq3
#eval Finite.beq (.arr .bool .bool) id (not ∘ not)
```
```anchorInfo arrBoolBoolEq3
true
```
This is because the {anchorName Finite}`Finite` universe codes for Lean's _actual_ function type, not a special analogue created by the library.
:::
The implementation of {anchorName FiniteAll}`enumerate` is also by recursion on the codes from {anchorName FiniteAll}`Finite`.
```anchor FiniteAll
def Finite.enumerate (t : Finite) : List t.asType :=
match t with
| .unit => [()]
| .bool => [true, false]
| .pair t1 t2 => t1.enumerate.product t2.enumerate
| .arr dom cod => dom.functions cod.enumerate
```
In the case for {anchorName Finite}`Unit`, there is only a single value.
In the case for {anchorName Finite}`Bool`, there are two values to return ({anchorName sundries}`true` and {anchorName sundries}`false`).
In the case for pairs, the result should be the Cartesian product of the values for the type coded for by {anchorName FiniteAll}`t1` and the values for the type coded for by {anchorName FiniteAll}`t2`.
In other words, every value from {anchorName FiniteAll}`dom` should be paired with every value from {anchorName FiniteAll}`cod`.
The helper function {anchorName ListProduct}`List.product` can certainly be written with an ordinary recursive function, but here it is defined using {kw}`for` in the identity monad:
```anchor ListProduct
def List.product (xs : List α) (ys : List β) : List (α × β) := Id.run do
let mut out : List (α × β) := []
for x in xs do
for y in ys do
out := (x, y) :: out
pure out.reverse
```
Finally, the case of {anchorName FiniteAll}`Finite.enumerate` for functions delegates to a helper called {anchorName FiniteFunctionSigStart}`Finite.functions` that takes a list of all of the return values to target as an argument.
Generally speaking, generating all of the functions from some finite type to a collection of result values can be thought of as generating the functions' tables.
Each function assigns an output to each input, which means that a given function has $`k` rows in its table when there are $`k` possible arguments.
Because each row of the table could select any of $`n` possible outputs, there are $`n ^ k` potential functions to generate.
Once again, generating the functions from a finite type to some list of values is recursive on the code that describes the finite type:
```anchor FiniteFunctionSigStart
def Finite.functions
(t : Finite)
(results : List α) : List (t.asType → α) :=
match t with
```
The table for functions from {anchorName Finite}`Unit` contains one row, because the function can't pick different results based on which input it is provided.
This means that one function is generated for each potential input.
```anchor FiniteFunctionUnit
| .unit =>
results.map fun r =>
fun () => r
```
There are $`n^2` functions from {anchorName sundries}`Bool` when there are $`n` result values, because each individual function of type {anchorTerm sundries}`Bool → α` uses the {anchorName sundries}`Bool` to select between two particular {anchorName sundries}`α`s:
```anchor FiniteFunctionBool
| .bool =>
(results.product results).map fun (r1, r2) =>
fun
| true => r1
| false => r2
```
Generating the functions from pairs can be achieved by taking advantage of currying.
A function from a pair can be transformed into a function that takes the first element of the pair and returns a function that's waiting for the second element of the pair.
Doing this allows {anchorName FiniteFunctionSigStart}`Finite.functions` to be used recursively in this case:
```anchor FiniteFunctionPair
| .pair t1 t2 =>
let f1s := t1.functions <| t2.functions results
f1s.map fun f =>
fun (x, y) =>
f x y
```
Generating higher-order functions is a bit of a brain bender.
Each higher-order function takes a function as its argument.
This argument function can be distinguished from other functions based on its input/output behavior.
In general, the higher-order function can apply the argument function to every possible argument, and it can then carry out any possible behavior based on the result of applying the argument function.
This suggests a means of constructing the higher-order functions:
* Begin with a list of all possible arguments to the function that is itself an argument.
* For each possible argument, construct all possible behaviors that can result from the observation of applying the argument function to the possible argument. This can be done using {anchorName FiniteFunctionSigStart}`Finite.functions` and recursion over the rest of the possible arguments, because the result of the recursion represents the functions based on the observations of the rest of the possible arguments. {anchorName FiniteFunctionSigStart}`Finite.functions` constructs all the ways of achieving these based on the observation for the current argument.
* For potential behavior in response to these observations, construct a higher-order function that applies the argument function to the current possible argument. The result of this is then passed to the observation behavior.
* The base case of the recursion is a higher-order function that observes nothing for each result value—it ignores the argument function and simply returns the result value.
Defining this recursive function directly causes Lean to be unable to prove that the whole function terminates.
However, using a simpler form of recursion called a _right fold_ can be used to make it clear to the termination checker that the function terminates.
A right fold takes three arguments: a step function that combines the head of the list with the result of the recursion over the tail, a default value to return when the list is empty, and the list being processed.
It then analyzes the list, essentially replacing each {lit}`::` in the list with a call to the step function and replacing {lit}`[]` with the default value:
```anchor foldr
def List.foldr (f : α → β → β) (default : β) : List α → β
| [] => default
| a :: l => f a (foldr f default l)
```
Finding the sum of the {anchorName sundries}`Nat`s in a list can be done with {anchorName foldrSum}`foldr`:
```anchorEvalSteps foldrSum
[1, 2, 3, 4, 5].foldr (· + ·) 0
===>
(1 :: 2 :: 3 :: 4 :: 5 :: []).foldr (· + ·) 0
===>
(1 + 2 + 3 + 4 + 5 + 0)
===>
15
```
With {anchorName foldrSum}`foldr`, the higher-order functions can be created as follows:
```anchor FiniteFunctionArr
| .arr t1 t2 =>
let args := t1.enumerate
let base :=
results.map fun r =>
fun _ => r
args.foldr
(fun arg rest =>
(t2.functions rest).map fun more =>
fun f => more (f arg) f)
base
```
The complete definition of {anchorName FiniteFunctions}`Finite.functions` is:
```anchor FiniteFunctions
def Finite.functions
(t : Finite)
(results : List α) : List (t.asType → α) :=
match t with
| .unit =>
results.map fun r =>
fun () => r
| .bool =>
(results.product results).map fun (r1, r2) =>
fun
| true => r1
| false => r2
| .pair t1 t2 =>
let f1s := t1.functions <| t2.functions results
f1s.map fun f =>
fun (x, y) =>
f x y
| .arr t1 t2 =>
let args := t1.enumerate
let base :=
results.map fun r =>
fun _ => r
args.foldr
(fun arg rest =>
(t2.functions rest).map fun more =>
fun f => more (f arg) f)
base
```
Because {anchorName MutualStart}`Finite.enumerate` and {anchorName FiniteFunctions}`Finite.functions` call each other, they must be defined in a {kw}`mutual` block.
In other words, right before the definition of {anchorName MutualStart}`Finite.enumerate` is the {kw}`mutual` keyword:
```anchor MutualStart
mutual
def Finite.enumerate (t : Finite) : List t.asType :=
match t with
```
and right after the definition of {anchorName FiniteFunctions}`Finite.functions` is the {kw}`end` keyword:
```anchor MutualEnd
| .arr t1 t2 =>
let args := t1.enumerate
let base :=
results.map fun r =>
fun _ => r
args.foldr
(fun arg rest =>
(t2.functions rest).map fun more =>
fun f => more (f arg) f)
base
end
```
This algorithm for comparing functions is not particularly practical.
The number of cases to check grows exponentially; even a simple type like {anchorTerm lots}`((Bool × Bool) → Bool) → Bool` describes {anchorInfoText nestedFunLength}`65536` distinct functions.
Why are there so many?
Based on the reasoning above, and using $`\left| T \right|` to represent the number of values described by the type $`T`, we should expect that
$$`\left| \left( \left( \mathtt{Bool} \times \mathtt{Bool} \right) \rightarrow \mathtt{Bool} \right) \rightarrow \mathtt{Bool} \right|`
is
$$`\left|\mathrm{Bool}\right|^{\left| \left( \mathtt{Bool} \times \mathtt{Bool} \right) \rightarrow \mathtt{Bool} \right| },`
which is
$$`2^{2^{\left| \mathtt{Bool} \times \mathtt{Bool} \right| }},`
which is
$$`2^{2^4}`
or 65536.
Nested exponentials grow quickly, and there are many higher-order functions.
# Exercises
%%%
tag := "universe-exercises"
%%%
* Write a function that converts any value from a type coded for by {anchorName Finite}`Finite` into a string. Functions should be represented as their tables.
* Add the empty type {anchorName sundries}`Empty` to {anchorName Finite}`Finite` and {anchorName FiniteBeq}`Finite.beq`.
* Add {anchorName sundries}`Option` to {anchorName Finite}`Finite` and {anchorName FiniteBeq}`Finite.beq`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.