Varaible name with space

Category:
Others
Description: Unlike other programming language, F# support a way to specify a variable name with space inside.
Code:
let VariableNameSample1() = 
let ``good one`` = 3
printfn "%d" ``good one``
Assert.AreEqual(``good one``, 3)

Execution Result:
3
both elements are equal

Keyword as variable name

Category:
Others
Description: Keyword as variable name. when need to use keyword as variable name, here is a way.
Code:
let VariableNameUseKeyword() = 
let ``let`` = 3
printfn "%d" ``let``
Assert.AreEqual(``let``, 3)

Execution Result:
3
both elements are equal

Serialization and Deserialization

Category:
Others
Description: Use Jason serializer to serialize and deserialize data.
Code:
let SerailizationAndDeserialization() = 
let serializeAndDeserialize (originalValue:'T) =
// Create a serializer, an output stream and serialzie the value
let serializer = DataContractJsonSerializer(typeof<'T>)
let out = new System.IO.MemoryStream()
printfn "input: %A" originalValue
serializer.WriteObject(out, originalValue)

// Get the serialized text
let text = out.ToArray() |> System.Text.Encoding.UTF8.GetString
out.Seek(0L, System.IO.SeekOrigin.Begin) |> ignore
printfn "serialized as: %s" text

let deserialziedValue = serializer.ReadObject out
printfn "deserialized as: %A" deserialziedValue

serializeAndDeserialize (1,2)
serializeAndDeserialize [| 1;2;3 |]
serializeAndDeserialize 1.01

let dict = new System.Collections.Generic.Dictionary()
dict.Add(2, "two")
dict.Add(3, "three")
serializeAndDeserialize dict

Execution Result:
input: (1, 2)
serialized as: {"m_Item1":1,"m_Item2":2}
deserialized as: (1, 2)
input: [|1; 2; 3|]
serialized as: [1,2,3]
deserialized as: [|1; 2; 3|]
input: 1.01
serialized as: 1.01
deserialized as: 1.01
input: seq [[2, two]; [3, three]]
serialized as: [{"Key":2,"Value":"two"},{"Key":3,"Value":"three"}]
deserialized as: seq [[2, two]; [3, three]]

Last edited Sep 12, 2011 at 11:42 PM by ttliu2000, version 1

Comments

No comments yet.