Browse Source

Exercise 2.2 Rewrite `member` to take no more than `d + 1` comparisions...

by keeping track of a candidate element that *might* be equal to the query element
and checking for equality only when you hit the bottom of the tree.
master
Aaron VonderHaar 4 years ago
parent
commit
e82f148f51
2 changed files with 102 additions and 0 deletions
  1. +87
    -0
      exercises/2.2 d + 1 comparisons/Main.elm
  2. +15
    -0
      exercises/2.2 d + 1 comparisons/elm-package.json

+ 87
- 0
exercises/2.2 d + 1 comparisons/Main.elm View File

@ -0,0 +1,87 @@
module UnbalancedSet exposing (..)
import Html exposing (Html)
type alias Ordered t =
{ eq : t -> t -> Bool
, lt : t -> t -> Bool
, leq : t -> t -> Bool
}
type Tree t
= E
| T (Tree t) t (Tree t)
type alias Set =
Tree
empty : Tree x
empty =
E
member : Ordered x -> x -> Tree x -> Bool
member compare x tree =
case tree of
E ->
False
T a y b ->
if
if compare.lt x y then
member compare x a
else
member compare x b
then
True
else
compare.eq x y
insert : Ordered x -> x -> Tree x -> Tree x
insert compare x tree =
case tree of
E ->
T E x E
T a y b ->
if compare.lt x y then
T (insert compare x a) y b
else if compare.lt y x then
T a y (insert compare x b)
else
tree
main : Html msg
main =
let
normal =
{ eq = \a b -> a == b
, lt = \a b -> a < b
, leq = \a b -> a <= b
}
debug =
{ eq = \a b -> Debug.log "eq" <| a == b
, lt = \a b -> Debug.log "lt" <| a < b
, leq = \a b -> Debug.log "leq" <| a <= b
}
in
empty
|> insert normal 4
|> insert normal 2
|> insert normal 1
|> insert normal 3
|> insert normal 7
|> insert normal 6
|> insert normal 8
|> insert normal 5
|> Debug.log "tree"
|> member debug 3
|> toString
|> Html.text

+ 15
- 0
exercises/2.2 d + 1 comparisons/elm-package.json View File

@ -0,0 +1,15 @@
{
"version": "1.0.0",
"summary": "helpful summary of your project, less than 80 characters",
"repository": "https://github.com/user/project.git",
"license": "BSD3",
"source-directories": [
"."
],
"exposed-modules": [],
"dependencies": {
"elm-lang/core": "4.0.1 <= v < 5.0.0",
"elm-lang/html": "1.0.0 <= v < 2.0.0"
},
"elm-version": "0.17.0 <= v < 0.18.0"
}

Loading…
Cancel
Save