Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure destructuring vs haskell-like argument pattern matching

Coming from Haskell I find it hard in Clojure to traverse some data types. In Haskell if I like to do some recursion on a type, in most basic case something like

foo (x : [])     = Just value
foo (x : y : xs) = bar y (foo xs)
foo _            = Nothing

is just fine.

But I think Clojure's destructuring is nothing near of being powerful as Haskell's pattern matching. Is there a nice idiomatic way to accomplish what I'm trying to do? For an example if I have a list/vector how can I match a case when there is no more elements and such?

like image 925
ayan ahmedov Avatar asked Mar 11 '26 05:03

ayan ahmedov


1 Answers

You can use core.match if desired

For example,

(defn foo [v] 
  (match v 
    [x] x
    [x y & more] (+ (* x y) (foo more)) 
    :else nil))
like image 126
A. Webb Avatar answered Mar 14 '26 01:03

A. Webb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!