learning F#, it seems pretty cool, favourite functional language so far.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

types.fsx 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. type IntAndBool = {intPart: int; boolPart: bool } // This is a `product` type. i.e. It is made from other simple types
  2. let x = {intPart=1; boolPart=false} // This is data of type `IntAndBool`
  3. type IntOrBool =
  4. | IntChoice of int
  5. | BoolChoice of bool // This is a `sum` type, i.e. it is made up of either simple type specified here
  6. let y = IntChoice 42
  7. let z = BoolChoice true
  8. // We can use types to achieve similar control flows to that of imperative languages.
  9. // Here is code that is analagous to an if-then-else construct
  10. let booleanExpression = true
  11. match booleanExpression with
  12. | true -> printfn "true" // Do things for true
  13. | false -> printfn "false" // Do things for false
  14. // Notice that this is very concise syntax and gets to the core of what we want to do
  15. // Here's a 'switch' statement
  16. let aDigit = 3
  17. match aDigit with
  18. | 1 -> printfn "1" // Do things for 1
  19. | 2 -> printfn "2" // Do things for 2
  20. | _ -> printfn "Something else" // like 'default' in switch
  21. // For loops are replaced with recursion
  22. let aList = [1;2;3]
  23. let rec printList list =
  24. match list with
  25. | [] -> [] // Empty
  26. | head::tail -> // Process first element, then recurse
  27. printfn "%d" head
  28. printList tail
  29. printList aList
  30. // To do something like polymorphism
  31. // we create `sum types`
  32. type Shape =
  33. | Circle of radius:int
  34. | Rectangle of height:int * width:int // Note tuples defined with '*'
  35. | Point of x:int * y:int
  36. | Polygon of pointList:(int * int) list
  37. let draw shape =
  38. match shape with
  39. | Circle radius -> printfn "The circle has radius: %d" radius
  40. | Rectangle (height, width) -> printfn "Height is %d" height // etc..
  41. | Polygon points -> points |> List.iter (printfn "%A") // you get it
  42. | _ -> printfn "I'm done"
  43. // Then you can do things with lists like:
  44. // shapes |> List.iter draw (imagine shapes is a list of shapes)