Skip to content

Instantly share code, notes, and snippets.

View dungpa's full-sized avatar

Anh-Dung Phan dungpa

View GitHub Profile
type Direction =
| Up
| Down
| Left
| Right
override this.ToString() =
match this with
| Up -> "Up"
| Down -> "Down"
| Left -> "Left"
@dungpa
dungpa / mistake7.fs
Created September 13, 2012 20:31
Common mistake
type Example() =
member __.Getter = doComputation()
// It's clearer if you use the long syntax:
type Example() =
member __.Getter with get() = doComputation()
// What you probably wanted to do is:
@dungpa
dungpa / mistake6.fs
Created September 13, 2012 20:30
Common mistake
type TickTack = Tick | Tack
let ticker x =
match x with
| Tick -> printfn "Tick"
| Tock -> printfn "Tock"
| Tack -> printfn "Tack"
ticker Tick
ticker Tack
@dungpa
dungpa / mistake5.fs
Created September 13, 2012 19:48
Common mistake
let main() =
let myIdent = "something ..."
...
...
...
let myFunc() =
let myIdent = "something else ..."
...
...
myIdent
@dungpa
dungpa / mistake4.fs
Created September 13, 2012 19:47
Common mistake
async {
let wc = new WebClient()
let html = wc.DownloadString(uri)
printfn "%s" html }
// To make code in F# async workflow actually asynchronous,
// we need to use a primitive operation of type Async<'T>
// (implemented usually in the F# library as an extension) and call it using let! or do!:
async {
@dungpa
dungpa / mistake3.fs
Created September 13, 2012 19:43
Common mistake
let plusOne (s : seq<_>) =
let e = s.GetEnumerator()
seq {
while e.MoveNext() do
yield e.Current + 1
}
let r = plusOne [1; 2; 3]
printfn "%A" r // prints [2; 3; 4]
printfn "%A" r // prints []
@dungpa
dungpa / mistake2.fs
Created September 13, 2012 19:40
A common mistake
let func =
printfn "hi"
1
// vs.
let func() =
printfn "hi"
1
@dungpa
dungpa / mistake1.fs
Created September 13, 2012 19:36
Async mistake 1
let rec loop () = async {
do! Async.Sleep(1000)
do! loop() } // Wrong!
// In order to write tail-recursive calls in F# async workflows, we should use return!:
let rec loop () = async {
do! Async.Sleep(1000)
return! loop() } // Correct :-)
@dungpa
dungpa / bootyDivision3.fs
Created July 30, 2012 14:18
Parallelism bits
// Preassign the divider with some configurations.
member x.preassignBB(level, threadId) =
for l in 1..level do
if threadId &&& (pown 2 l) <> 0 then
path.[depth] <- 1uy
totalValues.[1] <- totalValues.[1] + itemValues.[depth]
totalUnassigned <- totalUnassigned - itemValues.[depth]
depth <- depth + 1
else
path.[depth] <- 0uy
@dungpa
dungpa / bootyDivision2.fs
Created July 30, 2012 14:14
Branch and bound technique
// Using branch and bound method to prune unused branches.
member x.divideBB() =
if depth >= numItems then
if abs(totalValues.[0] - totalValues.[1]) < bestDifference then
Array.Copy(totalValues, bestTotalValues, size)
bestDifference <- abs(totalValues.[0] - totalValues.[1])
else ()
elif abs(totalValues.[0] - totalValues.[1]) - totalUnassigned <= bestDifference then
for i in 0..1 do
x.selectBB(i)