I recently made a crawl in clojure from F # and came across a macro called cond. Here is a usage example:
(cond (= target (nth arr mid)) mid (< target (nth arr mid)) (search left (- mid 1)) (> target (nth arr mid)) (search (+ mid 1) right) (= left right) -1)
This means the following in pseudo code:
if target == arr.[mid] then return mid if target < arr.[mid] then return (call search(left, mid-1)) if target > arr.[mid] then return (call search(mid+1, right)) if left == right then return -1
This is just a binary search example if you were wondering what was left to the right and in the middle, but not very important.
I tried to find something similar in F #, but I couldn’t, so I decided to try and write it for myself. I got something like this:
type condition = bool * int let cond (conds: condition seq) = conds |> Seq.pick(fun c -> if fst c then Some (snd c) else None) cond [| ( (=) target arr.[mid], mid ) ( (=) left right, -1 ) ( (<) target arr.[mid], recSrch left (mid-1) ) ( (>) target arr.[mid], recSrch (mid+1) right ) |]
The problem is that I want to use it in a recursive function and because recSrch left (mid-1) is evaluated immediately, so I end an infinite loop. I want this to be evaluated only on condition of fulfillment. In addition, the form is still not as clean as in Clojure.
Any ideas how I can improve this?
clojure f #
Peter V
source share