SlideShare a Scribd company logo
1 of 25
Functional Linear Data Structures
Form a Semantically Coherent Set
Jack Fox
jackfoxy.com  craftyThoughts
@foxyjackfox
Bibliography
jackfoxy.com/Lambda_Jam_fsharp_bibliography
Sample Code
github.com/jackfoxy/FunctionalLinearDataStructures
• Order
by construction / sorted / random
• Evaluation
eager / lazy
• Peek
first / last / indexed
• Construction
first / last / insert
• Remove (Deconstruct)
first / last / indexed
 choose 1
 choose 1
 choose 1 – 2, or #3
 choose 0 – 2, or #3
 choose 0 – 2, or #3
(insert only for sorted & random)
Seq lets you transform structures
let thisIsTrue =
seq {1..10}
|> Array.ofSeq
|> Deque.ofSeq
|> DList.ofSeq
|> FlatList.ofSeq
|> Heap.ofSeq false
|> LazyList.ofSeq
|> Queue.ofSeq
|> RandomAccessList.ofSeq
|> Vector.ofSeq
|> List.ofSeq = [1..10]
…and apply any of 68 Seq Module functions
seq {1.0..10.0} |> Heap.ofSeq false
|> Seq.average
seq {1..10} |> Deque.ofSeq
|> Seq.fold (fun state t -> (2 * t)::state) []
seq {1..10} |> RandomAccessList.ofSeq
|> Seq.mapi (fun i t -> i * t)
seq {1..10} |> Vector.ofSeq
|> Seq.reduce (fun acc t -> acc * t )
Unfold Infinite Sequences
unfold
starts
here
Markov chain
type Weather = Sunny | Cloudy | Rainy
let nextDayWeather today probability =
match (today, probability) with
| Sunny, p when p < 0.05 -> Rainy
| Sunny, p when p < 0.40 -> Cloudy
| Sunny, _ -> Sunny
| Cloudy, p when p < 0.30 -> Rainy
| Cloudy, p when p < 0.50 -> Sunny
| Cloudy, _ -> Cloudy
| Rainy, p when p < 0.15 -> Sunny
| Rainy, p when p < 0.75 -> Cloudy
| Rainy, _ -> Rainy
let NextState (today, (random:Random), i) =
let nextDay = nextDayWeather today (random.NextDouble())
printfn "day %i is forecast %A" i nextDay
Some (nextDay, (nextDay, random, (i + 1L)))
let forecastDays =
Seq.unfold NextState (Sunny, (new Random()), 0L)
printfn "%A" (Seq.take 5 forecastDays |> Seq.toList)
> day 0 is forecast Sunny
day 1 is forecast Sunny
day 2 is forecast Cloudy
day 3 is forecast Rainy
day 4 is forecast Cloudy
[Sunny; Sunny; Cloudy; Rainy; Cloudy]
printfn "%A" (Seq.skip 5 forecastDays |> Seq.take 5 |> Seq.toList)
> day 0 is forecast Sunny
…
day 9 is forecast Sunny
[Cloudy; Rainy; Sunny; Cloudy; Sunny]
printfn "don't try this at home! %i"
(Seq.length forecastDays)
printfn "don't try this at home either! %A"
(forecastDays |> List.ofSeq)
So far:
Linear Structures as an abstraction
Seq as the unifying abstraction
Sequences are sequential (duh!)
Next:
More choices
printfn "%A" (Seq.take 5 forecastDays |> Seq.toList)
printfn "%A" (Seq.take 7 forecastDays |> Seq.toList)
> day 0 is forecast Sunny
day 1 is forecast Cloudy
day 2 is forecast Sunny
day 3 is forecast Sunny
day 4 is forecast Cloudy
[Sunny; Cloudy; Sunny; Sunny; Cloudy]
day 0 is forecast Sunny
day 1 is forecast Sunny
day 2 is forecast Sunny
day 3 is forecast Sunny
day 4 is forecast Sunny
day 5 is forecast Sunny
day 6 is forecast Cloudy
[Sunny; Sunny; Sunny; Sunny; Sunny; Sunny; Cloudy]
Inconsistent!
LazyList: seq-like & List-like
let lazyWeatherList =
LazyList.unfold NextState (Sunny, (new Random()), 0L)
printfn "%A" (LazyList.take 3 lazyWeatherList)
> day 0 is forecast Sunny
day 1 is forecast Sunny
day 2 is forecast Cloudy
[Sunny; Sunny; Cloudy]
printfn "%A" (LazyList.take 4 lazyWeatherList)
> day 3 is forecast Cloudy
[Sunny; Sunny; Cloudy ; Cloudy]
Skip always evaluates
LazyList.ofSeq (seq {for i = 1 to 10 do
yield (nextItem i)})
|> LazyList.skip 2
|> LazyList.take 2
|> List.ofSeq
> item 1
item 2
item 3
item 4
O(1) Append
let observedWeatherList =
LazyList.ofList [Sunny; Sunny; Cloudy; Cloudy; Rainy;]
let combinedWeatherList =
LazyList.append observedWeatherList lazyWeatherList
printfn "%A" (LazyList.skip 4 combinedWeatherList
|> LazyList.take 3)
> day 0 is forecast Rainy
day 1 is forecast Cloudy
seq [Rainy; Rainy; Cloudy]
Observed Predicted
List - like
[ ]
Construct
Deconstruct
Tail
Hea
d
1
empt
y
:
:
…and the only data element
accessible!
Vector
54321
Construct
Deconstruct
Initia
l
Las
t
[ ]
empt
y
;
;
Multiway Forest
Multiway Tree
type 'a MultiwayTree = {Root: 'a; Children: 'a MultiwayForest}
with
…
and 'a MultiwayForest = 'a MultiwayTree Vector
let inline create root children = {Root = root; Children = children}
let inline singleton x = create x Vector.empty
Queue ::1 ;;
Deconstruct
Construct
DList ::1 ;;
Construct
Deconstruct
Construct
…
Tai
l
Hea
d
TaiHea
Breadth 1st Traversal
let inline breadth1stForest forest =
let rec loop acc dl =
match dl with
| DList.Nil -> acc
| DList.Cons(head, tail) ->
loop (Queue.conj head.Root acc)
(DList.append tail (DList.ofSeq head.Children))
loop Queue.empty (DList.ofSeq forest)
What are
We Missing?
We’ve seen
The right structure for the right job
RandomAccessList
54321
Construct
Deconstruct
Tai
l
Hea
d
[ ]
empt
y
:
:
Deque (double-ended queue)
5::1
Head Tail
;;
Init Last
Construct
Deconstruct
Construct
Deconstruct
Heap (ordered)
::1
Head Tail
Deconstruct
Construct
Graphics: http://www.turbosquid.com/3d-models/heap-gravel-max/668104
Deletions?
What Else?
Random Stack
Purely Functional Circular Buffer
Questions?

More Related Content

What's hot

Reactive X introduction part1
Reactive X introduction part1Reactive X introduction part1
Reactive X introduction part1Jieyi Wu
 
Project of data structure
Project of data structureProject of data structure
Project of data structureUmme habiba
 
Dynamically linked queues
Dynamically linked queuesDynamically linked queues
Dynamically linked queuesJonghoon Park
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureYaksh Jethva
 
Stacks overview with its applications
Stacks overview with its applicationsStacks overview with its applications
Stacks overview with its applicationsSaqib Saeed
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.CIIT Atd.
 
Reactive computing
Reactive computingReactive computing
Reactive computingStan Lea
 
Single State Atom apps
Single State Atom appsSingle State Atom apps
Single State Atom appsRogerio Chaves
 
Scala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en timeScala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en timekarianneberg
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTUREArchie Jamwal
 
Introduction to stack
Introduction to stackIntroduction to stack
Introduction to stackvaibhav2910
 
Akka stream and Akka CQRS
Akka stream and  Akka CQRSAkka stream and  Akka CQRS
Akka stream and Akka CQRSMilan Das
 

What's hot (18)

Reactive X introduction part1
Reactive X introduction part1Reactive X introduction part1
Reactive X introduction part1
 
Project of data structure
Project of data structureProject of data structure
Project of data structure
 
Stack
StackStack
Stack
 
Stack
StackStack
Stack
 
Dynamically linked queues
Dynamically linked queuesDynamically linked queues
Dynamically linked queues
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
 
Stacks overview with its applications
Stacks overview with its applicationsStacks overview with its applications
Stacks overview with its applications
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.
 
Reactive computing
Reactive computingReactive computing
Reactive computing
 
Single State Atom apps
Single State Atom appsSingle State Atom apps
Single State Atom apps
 
week-4x
week-4xweek-4x
week-4x
 
Scala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en timeScala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en time
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 
Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
 
Array list
Array listArray list
Array list
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
Introduction to stack
Introduction to stackIntroduction to stack
Introduction to stack
 
Akka stream and Akka CQRS
Akka stream and  Akka CQRSAkka stream and  Akka CQRS
Akka stream and Akka CQRS
 

Similar to Semantically coherent functional linear data structures

RではじめるTwitter解析
RではじめるTwitter解析RではじめるTwitter解析
RではじめるTwitter解析Takeshi Arabiki
 
ComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical SciencesComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical Sciencesalexstorer
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)riue
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxMihirDatir
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007Damien Seguy
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File Harjinder Singh
 
Reactive Programming with RxSwift
Reactive Programming with RxSwiftReactive Programming with RxSwift
Reactive Programming with RxSwiftScott Gardner
 
Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Leonardo Borges
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About RubyIan Bishop
 
Data manipulation with dplyr
Data manipulation with dplyrData manipulation with dplyr
Data manipulation with dplyrRomain Francois
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
Understanding reactive programming with microsoft reactive extensions
Understanding reactive programming  with microsoft reactive extensionsUnderstanding reactive programming  with microsoft reactive extensions
Understanding reactive programming with microsoft reactive extensionsOleksandr Zhevzhyk
 
Spark DataFrames for Data Munging
Spark DataFrames for Data MungingSpark DataFrames for Data Munging
Spark DataFrames for Data Munging(Susan) Xinh Huynh
 

Similar to Semantically coherent functional linear data structures (20)

RではじめるTwitter解析
RではじめるTwitter解析RではじめるTwitter解析
RではじめるTwitter解析
 
ComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical SciencesComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical Sciences
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
dplyr
dplyrdplyr
dplyr
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
 
Reactive Programming with RxSwift
Reactive Programming with RxSwiftReactive Programming with RxSwift
Reactive Programming with RxSwift
 
Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
array.ppt
array.pptarray.ppt
array.ppt
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
 
Data manipulation with dplyr
Data manipulation with dplyrData manipulation with dplyr
Data manipulation with dplyr
 
8558537werr.pptx
8558537werr.pptx8558537werr.pptx
8558537werr.pptx
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
CHAPTER 5
CHAPTER 5CHAPTER 5
CHAPTER 5
 
Understanding reactive programming with microsoft reactive extensions
Understanding reactive programming  with microsoft reactive extensionsUnderstanding reactive programming  with microsoft reactive extensions
Understanding reactive programming with microsoft reactive extensions
 
2 презентация rx java+android
2 презентация rx java+android2 презентация rx java+android
2 презентация rx java+android
 
Spark DataFrames for Data Munging
Spark DataFrames for Data MungingSpark DataFrames for Data Munging
Spark DataFrames for Data Munging
 

More from Jack Fox

Dependent Types make bad data unrepresentable
Dependent Types make bad data unrepresentableDependent Types make bad data unrepresentable
Dependent Types make bad data unrepresentableJack Fox
 
Dependent Types
Dependent TypesDependent Types
Dependent TypesJack Fox
 
Introduction to the lambda calculus
Introduction to the lambda calculusIntroduction to the lambda calculus
Introduction to the lambda calculusJack Fox
 
Tools for reading papers
Tools for reading papersTools for reading papers
Tools for reading papersJack Fox
 
Functional programming for production quality code
Functional programming for production quality codeFunctional programming for production quality code
Functional programming for production quality codeJack Fox
 
Intoduction to Homotopy Type Therory
Intoduction to Homotopy Type TheroryIntoduction to Homotopy Type Therory
Intoduction to Homotopy Type TheroryJack Fox
 
Type Theory and Practical Application
Type Theory and Practical ApplicationType Theory and Practical Application
Type Theory and Practical ApplicationJack Fox
 
F# for functional enthusiasts
F# for functional enthusiastsF# for functional enthusiasts
F# for functional enthusiastsJack Fox
 
Linear structures lightning talk
Linear structures lightning talkLinear structures lightning talk
Linear structures lightning talkJack Fox
 

More from Jack Fox (9)

Dependent Types make bad data unrepresentable
Dependent Types make bad data unrepresentableDependent Types make bad data unrepresentable
Dependent Types make bad data unrepresentable
 
Dependent Types
Dependent TypesDependent Types
Dependent Types
 
Introduction to the lambda calculus
Introduction to the lambda calculusIntroduction to the lambda calculus
Introduction to the lambda calculus
 
Tools for reading papers
Tools for reading papersTools for reading papers
Tools for reading papers
 
Functional programming for production quality code
Functional programming for production quality codeFunctional programming for production quality code
Functional programming for production quality code
 
Intoduction to Homotopy Type Therory
Intoduction to Homotopy Type TheroryIntoduction to Homotopy Type Therory
Intoduction to Homotopy Type Therory
 
Type Theory and Practical Application
Type Theory and Practical ApplicationType Theory and Practical Application
Type Theory and Practical Application
 
F# for functional enthusiasts
F# for functional enthusiastsF# for functional enthusiasts
F# for functional enthusiasts
 
Linear structures lightning talk
Linear structures lightning talkLinear structures lightning talk
Linear structures lightning talk
 

Recently uploaded

Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...
Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...
Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...ritikasharma
 
Nayabad Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Sex At ...
Nayabad Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Sex At ...Nayabad Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Sex At ...
Nayabad Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Sex At ...aamir
 
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
👙 Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service
👙  Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service👙  Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service
👙 Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Serviceanamikaraghav4
 
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...noor ahmed
 
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...noor ahmed
 
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser...Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser... Shivani Pandey
 
Beautiful 😋 Call girls in Lahore 03210033448
Beautiful 😋 Call girls in Lahore 03210033448Beautiful 😋 Call girls in Lahore 03210033448
Beautiful 😋 Call girls in Lahore 03210033448ont65320
 
Call Girls In Goa 9316020077 Goa Call Girl By Indian Call Girls Goa
Call Girls In Goa  9316020077 Goa  Call Girl By Indian Call Girls GoaCall Girls In Goa  9316020077 Goa  Call Girl By Indian Call Girls Goa
Call Girls In Goa 9316020077 Goa Call Girl By Indian Call Girls Goasexy call girls service in goa
 
Russian Escorts Agency In Goa 💚 9316020077 💚 Russian Call Girl Goa
Russian Escorts Agency In Goa  💚 9316020077 💚 Russian Call Girl GoaRussian Escorts Agency In Goa  💚 9316020077 💚 Russian Call Girl Goa
Russian Escorts Agency In Goa 💚 9316020077 💚 Russian Call Girl Goasexy call girls service in goa
 
Call Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service NashikCall Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser... Shivani Pandey
 
Call Girl Service Belur - 7001035870 with real photos and phone numbers
Call Girl Service Belur - 7001035870 with real photos and phone numbersCall Girl Service Belur - 7001035870 with real photos and phone numbers
Call Girl Service Belur - 7001035870 with real photos and phone numbersanamikaraghav4
 
👙 Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service
👙  Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service👙  Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service
👙 Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Serviceanamikaraghav4
 
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...Riya Pathan
 
Independent Sonagachi Escorts ✔ 9332606886✔ Full Night With Room Online Booki...
Independent Sonagachi Escorts ✔ 9332606886✔ Full Night With Room Online Booki...Independent Sonagachi Escorts ✔ 9332606886✔ Full Night With Room Online Booki...
Independent Sonagachi Escorts ✔ 9332606886✔ Full Night With Room Online Booki...Riya Pathan
 

Recently uploaded (20)

Russian ℂall gIRLS In Goa 9316020077 ℂall gIRLS Service In Goa
Russian ℂall gIRLS In Goa 9316020077  ℂall gIRLS Service  In GoaRussian ℂall gIRLS In Goa 9316020077  ℂall gIRLS Service  In Goa
Russian ℂall gIRLS In Goa 9316020077 ℂall gIRLS Service In Goa
 
Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...
Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...
Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...
 
Nayabad Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Sex At ...
Nayabad Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Sex At ...Nayabad Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Sex At ...
Nayabad Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Sex At ...
 
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Manjri Call Me 7737669865 Budget Friendly No Advance Booking
 
👙 Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service
👙  Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service👙  Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service
👙 Kolkata Call Girls Shyam Bazar 💫💫7001035870 Model escorts Service
 
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
 
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...
Independent Joka Escorts ✔ 8250192130 ✔ Full Night With Room Online Booking 2...
 
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
 
Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171
Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171
Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171
 
Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser...Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser...
 
Goa Call Girls 9316020077 Call Girls In Goa By Russian Call Girl in goa
Goa Call Girls 9316020077 Call Girls  In Goa By Russian Call Girl in goaGoa Call Girls 9316020077 Call Girls  In Goa By Russian Call Girl in goa
Goa Call Girls 9316020077 Call Girls In Goa By Russian Call Girl in goa
 
Beautiful 😋 Call girls in Lahore 03210033448
Beautiful 😋 Call girls in Lahore 03210033448Beautiful 😋 Call girls in Lahore 03210033448
Beautiful 😋 Call girls in Lahore 03210033448
 
Call Girls In Goa 9316020077 Goa Call Girl By Indian Call Girls Goa
Call Girls In Goa  9316020077 Goa  Call Girl By Indian Call Girls GoaCall Girls In Goa  9316020077 Goa  Call Girl By Indian Call Girls Goa
Call Girls In Goa 9316020077 Goa Call Girl By Indian Call Girls Goa
 
Russian Escorts Agency In Goa 💚 9316020077 💚 Russian Call Girl Goa
Russian Escorts Agency In Goa  💚 9316020077 💚 Russian Call Girl GoaRussian Escorts Agency In Goa  💚 9316020077 💚 Russian Call Girl Goa
Russian Escorts Agency In Goa 💚 9316020077 💚 Russian Call Girl Goa
 
Call Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service NashikCall Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
Call Girl Nashik Amaira 7001305949 Independent Escort Service Nashik
 
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...
 
Call Girl Service Belur - 7001035870 with real photos and phone numbers
Call Girl Service Belur - 7001035870 with real photos and phone numbersCall Girl Service Belur - 7001035870 with real photos and phone numbers
Call Girl Service Belur - 7001035870 with real photos and phone numbers
 
👙 Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service
👙  Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service👙  Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service
👙 Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service
 
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...
 
Independent Sonagachi Escorts ✔ 9332606886✔ Full Night With Room Online Booki...
Independent Sonagachi Escorts ✔ 9332606886✔ Full Night With Room Online Booki...Independent Sonagachi Escorts ✔ 9332606886✔ Full Night With Room Online Booki...
Independent Sonagachi Escorts ✔ 9332606886✔ Full Night With Room Online Booki...
 

Semantically coherent functional linear data structures

  • 1. Functional Linear Data Structures Form a Semantically Coherent Set Jack Fox jackfoxy.com  craftyThoughts @foxyjackfox Bibliography jackfoxy.com/Lambda_Jam_fsharp_bibliography Sample Code github.com/jackfoxy/FunctionalLinearDataStructures
  • 2. • Order by construction / sorted / random • Evaluation eager / lazy • Peek first / last / indexed • Construction first / last / insert • Remove (Deconstruct) first / last / indexed  choose 1  choose 1  choose 1 – 2, or #3  choose 0 – 2, or #3  choose 0 – 2, or #3 (insert only for sorted & random)
  • 3. Seq lets you transform structures let thisIsTrue = seq {1..10} |> Array.ofSeq |> Deque.ofSeq |> DList.ofSeq |> FlatList.ofSeq |> Heap.ofSeq false |> LazyList.ofSeq |> Queue.ofSeq |> RandomAccessList.ofSeq |> Vector.ofSeq |> List.ofSeq = [1..10]
  • 4. …and apply any of 68 Seq Module functions seq {1.0..10.0} |> Heap.ofSeq false |> Seq.average seq {1..10} |> Deque.ofSeq |> Seq.fold (fun state t -> (2 * t)::state) [] seq {1..10} |> RandomAccessList.ofSeq |> Seq.mapi (fun i t -> i * t) seq {1..10} |> Vector.ofSeq |> Seq.reduce (fun acc t -> acc * t )
  • 6. Markov chain type Weather = Sunny | Cloudy | Rainy let nextDayWeather today probability = match (today, probability) with | Sunny, p when p < 0.05 -> Rainy | Sunny, p when p < 0.40 -> Cloudy | Sunny, _ -> Sunny | Cloudy, p when p < 0.30 -> Rainy | Cloudy, p when p < 0.50 -> Sunny | Cloudy, _ -> Cloudy | Rainy, p when p < 0.15 -> Sunny | Rainy, p when p < 0.75 -> Cloudy | Rainy, _ -> Rainy
  • 7. let NextState (today, (random:Random), i) = let nextDay = nextDayWeather today (random.NextDouble()) printfn "day %i is forecast %A" i nextDay Some (nextDay, (nextDay, random, (i + 1L))) let forecastDays = Seq.unfold NextState (Sunny, (new Random()), 0L) printfn "%A" (Seq.take 5 forecastDays |> Seq.toList) > day 0 is forecast Sunny day 1 is forecast Sunny day 2 is forecast Cloudy day 3 is forecast Rainy day 4 is forecast Cloudy [Sunny; Sunny; Cloudy; Rainy; Cloudy]
  • 8. printfn "%A" (Seq.skip 5 forecastDays |> Seq.take 5 |> Seq.toList) > day 0 is forecast Sunny … day 9 is forecast Sunny [Cloudy; Rainy; Sunny; Cloudy; Sunny] printfn "don't try this at home! %i" (Seq.length forecastDays) printfn "don't try this at home either! %A" (forecastDays |> List.ofSeq)
  • 9. So far: Linear Structures as an abstraction Seq as the unifying abstraction Sequences are sequential (duh!) Next: More choices
  • 10. printfn "%A" (Seq.take 5 forecastDays |> Seq.toList) printfn "%A" (Seq.take 7 forecastDays |> Seq.toList) > day 0 is forecast Sunny day 1 is forecast Cloudy day 2 is forecast Sunny day 3 is forecast Sunny day 4 is forecast Cloudy [Sunny; Cloudy; Sunny; Sunny; Cloudy] day 0 is forecast Sunny day 1 is forecast Sunny day 2 is forecast Sunny day 3 is forecast Sunny day 4 is forecast Sunny day 5 is forecast Sunny day 6 is forecast Cloudy [Sunny; Sunny; Sunny; Sunny; Sunny; Sunny; Cloudy] Inconsistent!
  • 11. LazyList: seq-like & List-like let lazyWeatherList = LazyList.unfold NextState (Sunny, (new Random()), 0L) printfn "%A" (LazyList.take 3 lazyWeatherList) > day 0 is forecast Sunny day 1 is forecast Sunny day 2 is forecast Cloudy [Sunny; Sunny; Cloudy] printfn "%A" (LazyList.take 4 lazyWeatherList) > day 3 is forecast Cloudy [Sunny; Sunny; Cloudy ; Cloudy]
  • 12. Skip always evaluates LazyList.ofSeq (seq {for i = 1 to 10 do yield (nextItem i)}) |> LazyList.skip 2 |> LazyList.take 2 |> List.ofSeq > item 1 item 2 item 3 item 4
  • 13. O(1) Append let observedWeatherList = LazyList.ofList [Sunny; Sunny; Cloudy; Cloudy; Rainy;] let combinedWeatherList = LazyList.append observedWeatherList lazyWeatherList printfn "%A" (LazyList.skip 4 combinedWeatherList |> LazyList.take 3) > day 0 is forecast Rainy day 1 is forecast Cloudy seq [Rainy; Rainy; Cloudy] Observed Predicted
  • 14. List - like [ ] Construct Deconstruct Tail Hea d 1 empt y : : …and the only data element accessible!
  • 17. Multiway Tree type 'a MultiwayTree = {Root: 'a; Children: 'a MultiwayForest} with … and 'a MultiwayForest = 'a MultiwayTree Vector let inline create root children = {Root = root; Children = children} let inline singleton x = create x Vector.empty
  • 18. Queue ::1 ;; Deconstruct Construct DList ::1 ;; Construct Deconstruct Construct … Tai l Hea d TaiHea
  • 19. Breadth 1st Traversal let inline breadth1stForest forest = let rec loop acc dl = match dl with | DList.Nil -> acc | DList.Cons(head, tail) -> loop (Queue.conj head.Root acc) (DList.append tail (DList.ofSeq head.Children)) loop Queue.empty (DList.ofSeq forest)
  • 20. What are We Missing? We’ve seen The right structure for the right job
  • 22. Deque (double-ended queue) 5::1 Head Tail ;; Init Last Construct Deconstruct Construct Deconstruct
  • 23. Heap (ordered) ::1 Head Tail Deconstruct Construct Graphics: http://www.turbosquid.com/3d-models/heap-gravel-max/668104
  • 25. What Else? Random Stack Purely Functional Circular Buffer Questions?

Editor's Notes

  1. Bibliograhy and sandbox projects of all sample code.Linear is not just a powerful abstraction, it’s the most common raw organization e.g. Observable in reactive programming it’s also the most efficient physical organizationCall attention to obvious qualities of linear data along with linear primitives and performance considerations for functionalConsider how seq (IEnumerable) unifies functional linear structuresRichness of infinite sequences, joining finite and infinite, resolving repeatability requirement of functional
  2. It&apos;s fair to say the singly-linked list is the foundational linear data structure of functional programming. With it you can do most anything you can ask of a linear data structure or a linked data structure, but not always efficiently; and not just efficiency in terms of computational resources, but also expressively efficient.Disregarding for the moment range operations, let&apos;s look at the characteristics of and actions on linear data structures.Order is usually by construction, representing the order of the sequence consumed to create the structure, and/or the order individual elements were added. Sorted or even a random order is however possible.Evaluation in F# is eager by default, so you have to go out of your way to lazily evaluate anything (except sequences).Construction, peeking, and removing (or de-construction) are all the same for the singly-linked list (i.e. cons/tail), it always takes place at the beginning, but we might want a structure that mixes this up in any conceivable combination.If you work out the combinatorics, you would have a ridiculous number of potential signatures, but lazy evaluation for instance is not practical or desirable in most signatures, and there are only about a half dozen or so configurations that are uniquely useful as purely functional data structures.But the unifying theme here, indeed the concept that orients us across linear structures is sequence.
  3. The “banzai pipeline” of functional linear data structures. Only Heap potentially changes order (but not in this case).Trivially, Seq lets you seamlessly transform every linear data structure into any other, allowing you to take advantage of the qualities of first one and then another structure.
  4. Here’s another advantage of Seq. You have the entire repertoire of 68 module functions at your disposal for any linear data structure. The only reason you would ever want to natively implement one of these in your structure is if its internal representation lent itself to a faster native implementation. Note these functions don’t meet every need. Remember Seq is only forward processing, so foldback, for instance, is not available. Functions requiring anything but forward processing require a native implementation.
  5. Sequences serve not only as the common denominator of linear structures, but through the unfold function serve as data stream generators, and those sequences can be infinite. What would you do with this capability?
  6. How about Markov chains? We can take a real simple model of weather forecasting…
  7. …and create an infinite lazy sequence. This particular sequence won’t go on forever because I put a 64-bit counter in for demonstration purposes, but it will take a long time to blow-up. You’ll notice the demonstration print inside the generation function never fires until we actually instantiate the sequence into some kind of tangible data structure. This is what I mean by calling sequence a kind of phantom data structure.
  8. And no matter how hard you try, there is no way to take a shortcut down the infinite road. To get to a segment further down requires executing the entire intervening sequence.Since sequence can really represent an endless data stream, don’t instantiate the whole sequence or attempt to take its length.
  9. Here’s a quandary: reuse of my Markov Chain sequence will give inconsistent results because it is a probabilistic sequence. Our system is not idempotent.
  10. LazyList provides for infinite lazy streams, like sequence, but once computed an element’s result is cached. Beyond that LazyList functions like the standard singly-linked List.Think back on the qualities of sequential structures (order, evaluation, construction, peek). The combination rules lead to hundreds of theoretical structures, but only a handful have proved interesting. The practicalities of lazy evaluation make LazyList the most common lazy evaluated structure. But there is a performance penalty for implementing Lazy in a real F# structure, so only use LazyList when it makes sense.
  11. …and I attempted many different ways to circumvent this. Still no getting around executing intervening element cells.
  12. That being said, functional structures often have surprising efficiencies which come in handy. In this case LazyList does O(1) append. When would you use this? Well, think of joining observed and predicted data in your model. Weather models, stock market, extrapolating any kind of observed series.Note also F# type inference is labelling the LazyList collection data “seq”. This shows the versatility of implementing the seq interface, a.k.a. IEnumerable.
  13. At this point you may be suspecting some shortcomings in the sequential qualities available in both singly-linked List and LazyList. While consuming a data structure like observed and predicted weather progressing from beginning to end may feel natural, constructing a weather sequence by continually adding to the beginning is not the way you would probably want to do it. Imagine instead of appending predicted weather to observed weather, we cons’ed the observed weather onto the predicted weather LazyList. The observed weather series would have to be accessible in backwards order.And jumping to a random element, while possible, is clumsy.
  14. Enter the Vector. Indexed lookup and update are pretty close to constant time, O(log32n) if you are keeping score, construction and deconstruction at the end of the sequence, more in line with how humans normally think of extending a linear sequence. You would probably construct days of observed weather this way, for instance.Steffen Forkmann’s implementation of Vector from Clojure. It implements a hash array mapped trie internally. It’s very fast, gives you essentially all the functionality of F# Array, with the added qualities of persistence and the ability to grow and shrink efficiently at the end of the sequence. Vector is probably the most versatile and performant purely functional structure for covering most of your needs involving eager evaluation since it includes indexed lookup and update.
  15. Let&apos;s take the example of a Multiway Forest. Many kinds of documents can assume this form, HTML, XML, JSON docs, for example. We could model the sequences represented here with any linear data structure. Let&apos;s say it&apos;s Vector for arguments sake, and let&apos;s say the task at hand is to do a breadth first traversal.
  16. …and here’s the type of a Multiway Tree and Forest along with creation.
  17. Let&apos;s look at 2 more structures available in FSharpx.Collections. If you don&apos;t know about FSharpx, it&apos;s an open source foundational library for F# maintained in Github and available through NuGet.1) Queue, a persistent implementation of the well-known FIFO structure.2) DList (append list), this structure&apos;s signature in some ways marries the Queue and the singly linked list, with the added benefit we can not only enqueue single elements, but actually append an additional DList.So let&apos;s look at an example of how we can use purely functional linear structures to efficiently express program intent.
  18. The ease of composing linear structures lets us transform the forest segments across a range of structures. We use the canonical recursive loop over match.Our end product is a Queue so we seed it with an empty Queue, and start by transforming the top level forest segment into a DList. (Remember how sequence orients us across all linear structures? It also provides us with graceful transforms from any linear structure to any other.)Looping through the match, we deconstruct the DList into head and tail. Enqueue the data in the head element (note &quot;conj&quot; is the common function name across the FSharpx.Collections linear structures for adding an element on the right), and transform the head&apos;s children segment into a DList. This gets appended to the tail from the deconstruction and cycled through the loop. (Conveniently, &quot;append&quot; is an O(1) operation.)When the DList is empty output the accumulated Queue.
  19. But maybe we want to do some transformation not suited to Vector, like constructing and deconstructing at the front of the sequence.There’s an immutable structure for that. RandomAccessList is the dual of Vector. Same high performance, same indexed access to all elements, except construction and deconstruction happens at the front of the sequence.
  20. …and if you want to construct and deconstruct at both ends? The double-ended queue does construct, deconstruct, and peek from both ends, but now we are pushing the envelope of purely functional performance. You only ever have direct access to the elements at both ends, giving up indexed peek for any element. There’s also an amortized time complexity price to pay in terms of the internal structure supporting this purely functional arrangement.The functions on it however are perfectly symmetric.
  21. Okasaki delete using 2 heaps (one positive, one negative) as an “exercise for the reader”. This allows “future” deletes. One implementation in companion sandbox code.
  22. Value Oriented Programming might argue no room for deleting information, but we may want to kick an element out of a linear sequence.But so far everything has been O(1) or O(log32N), which is practically O(1)
  23. Random Stack and Circular Buffer left as “exercise for the reader”.