# Arrays and buffers # Buffers in Janet are the mutable version of strings (bytes). # Arrays are mutable, non-homogenous data structures # See: https://janet-lang.org/docs/data_structures/arrays.html # See: https://janet-lang.org/docs/data_structures/buffers.html (def arr1 @[1 2 3]) (def arr2 (array/new 4)) # Preallocate (put arr1 1 9) # Insert 9 at index 1 (put arr1 2 "aaa") # Non-homogenous # From haskells sum = foldl (+) 0 (defn mysum [x] (reduce + 0 x)) (assert (= (mysum [1 2 3]) (sum [1 2 3]))) # These are all equal (print (= (get arr1 1) (1 arr1) (arr1 1))) (print (get arr1 10 :default)) # Default value (pp arr1) # pp for "pretty print" # Structs and tables (def strct {:a "b" :c "k"}) (def tabl @{:a "b" :c "k"}) (put tabl :b "c") (def val (get tabl :b)) (def person {:name "kevin" :age 10}) (def p (struct :key "value" :oki 12)) # Tuples (vectors?) # See: https://janet-lang.org/docs/data_structures/tuples.html (def t [1 2 3 4]) (loop [num :in t] (prin num)) (print) (loop [x :range [0 3] y :range [0 3]] (prin x y)) (defn main [& argv] (var filtered @{}) (var root (os/dir "/")) (defn push [p] (put filtered p 0)) (each p root (push p)) (loop [p :in root] (push p)) (map push root) (map prin (keys filtered))) # Functions (defn addone [x] (+ x 1)) # Shorthand way (def addtwo (fn [x] (+ x 2))) # Full way (defn destr [l & rest] "Recursive function with destructuring arguments" (pp l) (if (> (length rest) 0) (destr rest))) (defn fn1 [fst & more] "Recursive 2" (print fst) (when (not (empty? more)) (apply fn1 more))) # Optional parameters (defn add [x &opt y] (default y 5) (+ x y)) (def f1 (partial + 5)) (def f2 (fn [x] (+ x 5))) (def f3 (fn named [x] (+ x 5))) (print (f1 5)) # 10 (print (f2 5)) # 10 (print (f3 5)) # 10 (defn my-adder "Adds numbers in a dubious way." [& xs] (var accum 0) (each x xs (+= accum (- (* 2 x) x))) accum) (my-adder 1 2 3) # -> 6 # Higher order functions (defn higher [f x] (f x)) # Takes a function which it then applies to x (defn add [x &opt y] (default y 5) (+ x y)) (print (higher add 1332)) (print (higher (partial add 0) 1332)) # Currying from wish (fn1 1 2 3 4) (destr [1 2 3 4 5]) (def ip-address '{:dig (range "09") :0-4 (range "04") :0-5 (range "05") :byte (choice (sequence "25" :0-5) (sequence "2" :0-4 :dig) (sequence "1" :dig :dig) (between 1 2 :dig)) :main (sequence :byte "." :byte "." :byte "." :byte)}) (peg/match ip-address "0.0.0.0") # -> @[] (peg/match ip-address "elephant") # -> nil (peg/match ip-address "256.0.0.0") # -> nil (peg/match ip-address "0.0.0.0more text") # -> @[]