Advertisement
Guest User

Untitled

a guest
May 24th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. (defn abstractOp [action]
  2. (fn [& args]
  3. {:pre [(= (count args) (count (filter #(or (number? %) ( = (count (first args)) (count %))) args)))]}
  4. (apply mapv action args)))
  5.  
  6. (def v+ (abstractOp +))
  7. (def v- (abstractOp -))
  8. (def v* (abstractOp *))
  9.  
  10. (defn scalar [& args] (reduce + (reduce v* args)))
  11. (defn vectHelp [a, b, i, j] (- (* (a i) (b j)) (* (a j) (b i))))
  12. (defn vect [& args]
  13. {:pre [(= (count args) (count (filter #(= (count (first args)) (count %)) args)))]}
  14. (reduce (fn [a, b] [(vectHelp a b 1 2), (vectHelp a b 2 0), (vectHelp a b 0 1)]) args))
  15. (defn v*s [a & s] (mapv #(* % (reduce * s)) a))
  16.  
  17. (def m+ (abstractOp v+))
  18. (def m- (abstractOp v-))
  19. (def m* (abstractOp v*))
  20. (defn m*s [a & s] (mapv #(v*s % (reduce * s)) a))
  21. (defn m*v [m, v]
  22. (mapv (fn [x] (scalar x v)) m))
  23.  
  24. (defn transpose [m]
  25. (apply mapv vector m))
  26.  
  27. (defn m*m [& args] (reduce (fn [m, p]
  28. (let [tr_p (transpose p)]
  29. (mapv (partial m*v tr_p) m))) args))
  30.  
  31. (defn myF [action actionS args]
  32. (if (number? (first args))
  33. (apply action args)
  34. (apply (abstractOp actionS) args)))
  35.  
  36. (defn s+ [& args] (myF + s+ args))
  37. (defn s- [& args] (myF - s- args))
  38. (defn s* [& args] (myF * s* args))
  39.  
  40. ;correct
  41. ;(defn myF [action actionS]
  42. ; (fn [args]
  43. ; (if (number? (first args))
  44. ; (apply action args)
  45. ; (apply (abstractOp actionS) args))))
  46. ;
  47. ;(defn s+ [& args] ((myF + s+) args))
  48. ;
  49. ;incorrect
  50. ;(defn myF2 [action actionS]
  51. ; (fn [& args]
  52. ; (if (number? (first args))
  53. ; (apply action args)
  54. ; (apply (abstractOp actionS) args))))
  55. ;
  56. ;(def s+ (myF2 + s+))
  57.  
  58. (defn getForm [x]
  59. (loop [x x ans []]
  60. (if (number? x)
  61. ans
  62. (recur (first x) (conj ans (count x))))))
  63.  
  64. (defn broadcast [x y action]
  65. (let [fx (getForm x) fy (getForm y)]
  66. (if (< (count fx) (count fy))
  67. (loop [i (- (count fy) (count fx) 1) x x]
  68. (if (< i 0)
  69. (action x y)
  70. (recur (dec i) (vec (repeat (nth fy i) x)))))
  71. (loop [i (- (count fx) (count fy) 1) y y]
  72. (if (< i 0)
  73. (action x y)
  74. (recur (dec i) (vec (repeat (nth fx i) y))))))))
  75.  
  76.  
  77. (defn b+ [& args] (reduce #(broadcast %1 %2 s+) args))
  78.  
  79. (defn b- [& args]
  80. (if (= (count args) 1)
  81. (s- (first args))
  82. (reduce #(broadcast %1 %2 s-) args)))
  83.  
  84. (defn b* [& args] (reduce #(broadcast %1 %2 s*) args))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement