JanetDocsPlaygroundI'm feeling luckyGitHub sign in

JanetDocs is a community documentation site for the Janet programming language

Loading...

Recent examples

# channels that can be used for communication between os threads
(def chan-a (ev/thread-chan 10))
(def chan-b (ev/thread-chan 10))

# one thread
(ev/thread
  (fiber/new
    (fn []
      (def msg "hi")
      (print "thread 1 sending: " msg)
      (ev/give chan-a msg)
      #
      (print "thread 1 received: " (ev/take chan-b))))
  :1
  :n)

# another thread
(ev/thread
  (fiber/new
    (fn []
      (print "thread 2 received: " (ev/take chan-a))
      #
      (def msg "peace")
      (print "thread 2 sending: " msg)
      (ev/give chan-b msg)))
  :2
  :n)

# expected output
#
# thread 1 sending: hi
# thread 2 received: hi
# thread 2 sending: peace
# thread 1 received: peace
ev/threadsogaiuPlayground
# channel that can be used for communication between os threads
(def chan (ev/thread-chan 10))

# one thread for sending a message
(ev/do-thread
  (def msg "hi")
  (print "sending: " msg)
  (ev/give chan msg))

# another thread for receiving a message
(ev/do-thread
  (print "received: " (ev/take chan)))

# expected output
#
# sending: hi
# received: hi
ev/do-threadsogaiuPlayground
(string/format "%f" (os/clock)) # => "1627746483.991000"
os/clockdbreadyPlayground
# Get a new and different random number each time you run your program.
(math/seedrandom (os/cryptorand 8))
(math/random)
math/randomuvtcPlayground
# Gathers all of the calls of "declare-" into a table from the project.janet file at path
(defn capture-declares [path] 
    (def *capture* @{})
    (defn append-capture [name & arg]
      (update *capture* name (fn [val] (array/push (or val @[]) ;arg))))
    (defn only-captures [form] 
      (when (string/has-prefix? "declare-" (string (form 0)))
        (append-capture (form 0) (slice form 1))
        form)
      nil)
    (dofile path :expander only-captures)
    *capture*)
dofileyumaikasPlayground
(invert [(chr "y") (chr "o")])
# => @{111 1 121 0}
invertsogaiuPlayground
(from-pairs [[:a 1] [:b 2]])
# => @{:a 1 :b 2}
from-pairsswlkrPlayground
(var x 10)

(unless (= x 10)
   (print "x is not 10!")
   (print "x is 10!"))

# => "x is 10!"
unlessHoangTuan110Playground
(var n 5) # n = 5
(-= n 1) # n -= 1
(print n) # 4
-=HoangTuan110Playground
(def s (symbol/slice :hello 2 4))

(print (type s)) # symbol
(print s)        # ll
symbol/slicewrqPlayground
(defn greet-me [] (print "hey programmer!"))
(defn greet-stranger [] (print "hey stranger!"))

(varfn greet [] (greet-me))
(greet) # prints "hey programmer!"
(varfn greet [] (greet-stranger))
(greet) # prints "hey stranger!"

# kind of analogous to (def greet (fn [] (some-thunk))), but with built-in
# sugar to automatically update 'greet' if varfn is called with a name
# already bound
varfnwrqPlayground
(doc doc) # works
(doc* doc) # symbol <function doc> not found
(doc* "doc") # same as (doc doc)
doc*skuzzymigletPlayground
(disasm +)
# {:max-arity 2147483647
#  :constants @[]
#  :name "+"
#  :defs @[]
#  :vararg true
#  :environments @[]
#  :arity 0
#  :slotcount 6

#  :bytecode
#  @[(len 1 0)
#    (eqim 2 1 0)
#    (jmpno 2 3)
#    (ldi 3 0)
#    (ret 3)
#    (eqim 2 1 1)
#    (jmpno 2 5)
#    (ldi 3 0)
#    (geti 4 0 0)
#    (add 3 3 4)
#    (ret 3)
#    (geti 3 0 0)
#    (ldi 5 1)
#    (in 4 0 5)
#    (add 3 3 4)
#    (addim 5 5 1)
#    (eq 2 5 1)
#    (jmpno 2 -4)
#    (ret 3)]
#  :min-arity 0}
disasmskuzzymigletPlayground
(var x 5)
(%= x 3)
(pp x) # 2
%=skuzzymigletPlayground
(defn walker
  `Simple walker function, that prints non-sequential 
   members of the form or prints "Sequence" and walks 
   recursively sequential members of the tree.` 
  [form] 
  (if (or (indexed? form) (dictionary? form))
    (do (print "Sequence")
        (walk walker form))
    (print form)))

(walk walker [[[[0 1 3]] 16 7 [3 [3 5]] 3 4] 1 [3 4]])

# Prints
# Sequence
# Sequence
# Sequence
# 0
# 1
# 3
# 16
# 7
# Sequence
# 3
# Sequence
# 3
# 5
# 3
# 4
# 1
# Sequence
# 3
# 4
walkpepePlayground
(def error-levels {:red 3 :orange 2 :yellow 1})

# Create a new prototype object called ErrorProto with one method, :compare
(def ErrorProto
  @{:level nil

    # Returns -1, 0, 1 for x < y, x = y, x > y respectively.
    :compare (fn [self other]
               (let [lx (error-levels (self :level))
                     ly (error-levels (other :level))]
                 (cond
                   (< lx ly) -1
                   (> lx ly) 1
                   :else 0)))})

# Factory function to create new Error objects 
(defn make-error
  [level]
  (table/setproto @{:level level} ErrorProto))


(def err-red (make-error :red))
(def err-yell (make-error :yellow))
(def err-orange (make-error :orange))

# calls of the polymorphic compare function
(compare err-red err-orange) # 1
(compare err-orange err-red) # -1
(compare err-red err-red)    # 0

# These following functions call internally 
# the polymorphic compare function, but return a boolean value
(compare> err-red err-orange)  # true
(compare> err-yell err-orange) # false
(compare= err-yell err-yell)   # true

#-------------------------------------------------------------------------------
# sort the objects with compare> and compare<

(def errors-unsorted @[err-red err-yell err-orange])

# ascending order
(sort errors-unsorted compare<) 
# => @[@{:level :yellow} @{:level :orange} @{:level :red}]

# descending order
(sort errors-unsorted compare>) 
# => @[@{:level :red} @{:level :orange} @{:level :yellow}]

# without compare
(sort-by |(error-levels ($ :level)) errors-unsorted)
# => @[@{:level :yellow} @{:level :orange} @{:level :red}]

# Note!!!, the following does not work as expected. 
# sort alone does not automatically use the compare function (the comparator)
(sort errors-unsorted) # result is not sorted!
compareleobmPlayground
# create a channel without buffer, default is 0
(def channel (ev/chan))

(ev/spawn
  (ev/sleep 5)
  (ev/give channel "Hard work is done!"))

(print "do anything")
(for i 0 5
  (print i)
  (ev/sleep 0.5))

(print (ev/take channel)) # blocks here, until there is a result in the channel
(print "done")

ev/chanleobmPlayground
(for i 0 5 
     (print i))
 
# 0
# 1
# 2
# 3
# 4

# => nil
forleobmPlayground
# with by function 

(sorted [1 -2 2 3 9 -10] >)  #@[9 3 2 1 -2 -10]
sortedleobmPlayground
# slice with strings
(slice "Hello" 1)        # => "ello"
(slice "Playing" 0 -4)   # => "Play"
(slice "Playing" -4)     # => "ing"

# slice with keyword
(slice :hello 1)         # => "ello"
sliceleobmPlayground
(var buf @"")
(buffer/push-word buf 2147483647)

(+
  (get buf 0)                # byte 1
  (blshift (get buf 1) 8)    # byte 2
  (blshift (get buf 2) 16)   # byte 3
  (blshift (get buf 3) 24))  # byte 4

# => 2147483647
buffer/push-wordleobmPlayground
# access tuple values

(def t [:a :b :c]) # test tuple

(first t)
# => :a

(last t)
# => :c

(slice t 0 2)
# => (:a :b)

# Index as function
(0 t)
# => :a

# Tuple as function
(t 0)
# => :a

# With destructuring
(let [[_ b _] t] 
    b)
# => :b

# With pattern matching
(match t
    [:a _ :d] (print "does not match")
    [:a b :c] (print b)
    _         (print "anything"))

# => :b
tupleleobmPlayground
(frequencies ["a" "a" "b" "c" "d" "d"])
# => @{"c" 1 "d" 2 "a" 2 "b" 1}


(frequencies {:a "Bob"
              :b "Joe"
              :c "Mat"
              :d "Bob"})
# => @{"Bob" 2 "Joe" 1 "Mat" 1}

(frequencies "Hallo World")
# => @{108 3 114 1 100 1 87 1 97 1 32 1 111 2 72 1}
frequenciesleobmPlayground
# :when modifier argument example

(let [even-numbers  @[]]
    (loop [i :range [0 50] :when (even? i)]
        (array/push even-numbers i))
    even-numbers)

# => @[0 2 4 6 8 10 12 14 16 1.....]
loopleobmPlayground
# build own map-indexed with map

(defn map-indexed [f ds]
    (map f (range 0 (length ds)) ds))

(map-indexed (fn [i v] [i v] ) ["a" "b" "c" "d"])

# => @[(0 "a") (1 "b") (2 "c") (3 "d")]
mapleobmPlayground
(filter identity [1 true 2 3 nil 4 false])
# => @[1 true 2 3 4]
identityleobmPlayground
(find |(= 2 $) {:a 1 :b 2 :c 3})
# => 2

(get @"Hello" 1)
# => 101

(find |(= 101 $)  @"Hello")
# => 101

(find |(> $ 3)  {:a 1 :b 2 :c 3})
# => nil
findleobmPlayground
(as?-> [1 2 3] _ 
  (sum _)
  (when (> 6 _) _))
# => nil

(as?-> [1 2 3] _ 
  (sum _)
  (when (>= 6 _) _))

# => 6
as?->leobmPlayground
(interleave [:a :b :c] [1 2 3]) 
# => @[:a 1 :b 2 :c 3]

(interleave [:a :b :c] (range 3)) 
# => @[:a 0 :b 1 :c 2]

(interleave [:a :b :c] (range 2)) 
# => @[:a 0 :b 1]

(struct ;(interleave [:a :b :c] [1 2 3]))
# {:c 3 :a 1 :b 2}

(table ;(interleave [:a :b :c] [1 2 3]))
# @{:c 3 :a 1 :b 2}
interleaveleobmPlayground
(any? "")
# => nil

(any? "Hello")
# => 72

(any? @"Hello")
# => 72

(any? @[])
# => nil

(any? [])
# => nil

(any? {})
# => nil

(any? @{})
# => nil

(any? @[1 2 3 4])
# => 1 

(any? @{:a 2 :b 3})
# => 2
any?leobmPlayground