fork(1) download
  1. (*
  2.   Swift's closure
  3.   https://d...content-available-to-author-only...e.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html
  4. *)
  5.  
  6.  
  7. load "Intmap"; (* for Moscow ML *)
  8.  
  9.  
  10. fun unfoldr_string f b = case f b of
  11. SOME (a, b') => a ^ (unfoldr_string f b')
  12. | NONE => ""
  13.  
  14. fun unfoldl_string f b = case f b of
  15. SOME (a, b') => (unfoldl_string f b') ^ a
  16. | NONE => ""
  17.  
  18.  
  19. val digitNames = foldr
  20. (fn ((i, s), m) => Intmap.insert (m, i, s))
  21. (Intmap.empty ())
  22. [
  23. (0, "Zero"), (1, "One"), (2, "Two"), (3, "Three"), (4, "Four"),
  24. (5, "Five"), (6, "Six"), (7, "Seven"), (8, "Eight"), (9, "Nine")
  25. ]
  26. val numbers = [16, 58, 510]
  27.  
  28.  
  29. val strings = map
  30. (
  31. fn number => unfoldl_string
  32. (fn (num, output) =>
  33. if num <= 0 then
  34. NONE
  35. else
  36. SOME (
  37. Intmap.retrieve (digitNames, num mod 10) ^ output,
  38. (num div 10, output)
  39. )
  40. )
  41. (number, "")
  42. )
  43. numbers
  44.  
  45.  
  46. fun print_strings xs = (
  47. (map (fn s => (print (s ^ "\n") ; ())) xs) ;
  48. ()
  49. )
  50.  
  51.  
  52.  
  53. (****
  54.  
  55. $ mosml numbers-map-haskell.sml
  56. Moscow ML version 2.01 (January 2004)
  57. Enter `quit();' to quit.
  58. [opening file "numbers-map-haskell.sml"]
  59. > val it = () : unit
  60. > val 'a unfoldr_string = fn : ('a -> (string * 'a) option) -> 'a -> string
  61.   val 'a unfoldl_string = fn : ('a -> (string * 'a) option) -> 'a -> string
  62.   val digitNames = <intmap> : string intmap
  63.   val numbers = [16, 58, 510] : int list
  64.   val strings = ["OneSix", "FiveEight", "FiveOneZero"] : string list
  65.   val print_strings = fn : string list -> unit
  66. [closing file "numbers-map-haskell.sml"]
  67. - print_strings strings;
  68. OneSix
  69. FiveEight
  70. FiveOneZero
  71. > val it = () : unit
  72. -
  73.  
  74. ****)
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
File "prog.ml", line 10, characters 23-24:
Syntax error
stdout
Standard output is empty