Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. (ns assign2prop.core)
  2. (import java.io.FileReader java.io.File)
  3. (import java.io.Closeable)
  4.  
  5. ;If an exception is thrown inside the expression the exception should be returned.
  6. ;Otherwise the evaluated value of the expression should be returned. If a binding is
  7. ;provided it should be possible to use the bound variable inside the expression.
  8. ;
  9. ;
  10. ; After
  11. ;execution of the form any variables that are bound shall be closed (e.g.
  12. ; (let [s (Socket.)] (. s close))) Note that closeable classes in Java implements
  13. ;the Closeable–interface (hint: use type hints). The return value of the macro
  14. ;is either the return value of the executed form or an exception.
  15. ;(defmacro safe [vect expr]
  16. ; ; ta index 0 i vect och sätt till index 1 i vect (kombinera)
  17. ;
  18. ; `(let [~(symbol (first vect)) (FileReader. (File. "C:\\Users\\dogge\\IdeaProjects\\assign2prop\\src\\assign2prop\\text.txt"))])
  19. ;
  20. ; )
  21.  
  22. (defmacro safe [& parameters]
  23. (if (>(count parameters) 1)
  24.  
  25. `(try
  26. (let ~(first parameters) (def x ~(second parameters))
  27. (if (instance? Closeable ~(ffirst parameters))
  28. (.close ~(ffirst parameters))) x)
  29. (catch Exception e# (str "Exception caught: " e#)))
  30.  
  31. `(try
  32. ~@parameters
  33. (catch Exception e# (str "Exception caught: " e#)))))
  34.  
  35.  
  36. (defn -main []
  37. (def v (safe (/ 1 0)))
  38. (println v)
  39. (def v (safe [s (FileReader. (File. "C:\\\\temp\\\\file.txt"))] (.read s)))
  40.  
  41. (println v)
  42. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement