Advertisement
tinyevil

Untitled

Mar 20th, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. Require Import String.
  2. Require Import Ascii.
  3. Require Import ZArith.
  4. Load Base10.
  5. Open Scope Z.
  6. Open Scope string.
  7.  
  8. Inductive PrintDirective :=
  9. | FormatLit : ascii -> PrintDirective
  10. | FormatNum : PrintDirective
  11. | FormatString : PrintDirective
  12. | FormatChar : PrintDirective.
  13.  
  14. Definition PrintFormat := list PrintDirective.
  15.  
  16. Definition directiveType (dir : PrintDirective) :=
  17. match dir with
  18. | FormatLit _ => None
  19. | FormatNum => Some Z
  20. | FormatString => Some string
  21. | FormatChar => Some ascii
  22. end.
  23.  
  24. Fixpoint formatType (f : PrintFormat) : Set :=
  25. match f with
  26. | nil => string
  27. | cons dir dirs =>
  28. match directiveType dir with
  29. | Some T => T -> formatType dirs
  30. | None => formatType dirs
  31. end
  32. end.
  33.  
  34. Fixpoint sprintf (f : PrintFormat) (k:string->string) : formatType f :=
  35. match f with
  36. | nil => k EmptyString
  37. | cons dir dirs =>
  38. match dir with
  39. | FormatLit c => sprintf dirs (fun rest => k (String c rest))
  40. | FormatNum => fun z => sprintf dirs (fun rest => k (z_to_str z ++ rest))
  41. | FormatString => fun s => sprintf dirs (fun rest => k (s ++ rest))
  42. | FormatChar => fun c => sprintf dirs (fun rest => k (String c rest))
  43. end
  44. end.
  45.  
  46. Fixpoint parse_format (fmt:string) : PrintFormat :=
  47. match fmt with
  48. | String "%" (String "s" xs) => cons FormatString (parse_format xs)
  49. | String "%" (String "d" xs) => cons FormatNum (parse_format xs)
  50. | String "%" (String "c" xs) => cons FormatChar (parse_format xs)
  51. | String x xs => cons (FormatLit x) (parse_format xs)
  52. | EmptyString => nil
  53. end.
  54.  
  55. Definition printf (fmt:string) := sprintf (parse_format fmt) (fun s=>s).
  56.  
  57. Compute (
  58. printf "number is %d, character is %c, string is %s"
  59. 12
  60. ("Z"%char)
  61. "meduzik"
  62. : string).
  63. (* = "number is 12, character is Z, string is meduzik"
  64. : string *)
  65.  
  66. Fail Compute (
  67. printf "number is %d, expected a number here: %d, character is %c, string is %s"
  68. 12
  69. ("Z"%char)
  70. "meduzik"
  71. : string).
  72. (* The command has indeed failed with message:
  73. The term ""Z"%char" has type "ascii" while it is expected to have type
  74. "Z".
  75. *)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement