JanetDocsPlaygroundI'm feeling luckyGitHub sign in

JanetDocs is a community documentation site for the Janet programming language

Loading...

Recent examples

(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
math/e 
# => 2.71828
math/eleobmPlayground
# in struct 
(index-of 2 {:a 1 :b 2 :c 3 :d 2} )
# => :b

# in table 
(index-of 2 @{:a 1 :b 2 :c 3 :d 2})
# => :b

# in array 
(index-of 6 @[4 5 6 7 8 9] )
# => 2

# in tuple 
(index-of 2 [1 2 3 4])
# => 1
index-ofleobmPlayground
(def f (generate [i :range [0 5]] (+ i i)))

(print (fiber/status f))
(print (resume f)) 
(print (resume f)) 
(print (resume f)) 
(print (resume f)) 
(print (resume f)) 
(print (fiber/status f)) # -> :pending
(print (resume f)) 
(print (fiber/status f)) # -> :dead


# :new
# 0
# 2
# 4
# 6
# 8
# :pending
#
# :dead
generateleobmPlayground
(>= 4 2)
# => true 

# multiple values
(>= 4 4 3 2 1 1)
# => true 

# with array in apply call
(apply >= [4 4 3 2 1 1])
# => true 

# with array in splice form
(>= ;[4 4 3 2 1 1])
# => true 
>=leobmPlayground
(def name "Joe")
(when (= name "Joe") "Hello Joe")
# "Hello Joe"


(when (not= 1 2) "not-equal")
# "not-equal"
whenleobmPlayground
# uses the fn shorthand
(take-until |(< 3 $) [0 1 2 3 4 5 6 7 8])
# (0 1 2 3)

# uses partial
(take-until (partial < 3) [0 1 2 3 4 5 6 7 8])
# (0 1 2 3)
take-untilleobmPlayground
(drop-while |(> 3 $) [0 1 2 3 4 5 6 7 8 ])
# => (3 4 5 6 7 8)
drop-whileleobmPlayground
(string/split "\n" @"works\nfor\nbuffers\ntoo")
# => @["works" "for" "buffers" "too"]
string/splitsogaiuPlayground
(def a @[[42 "c"] [68 "b"] [31 "d"] [27 "a"]])
(sort a (fn [a b]
          (< (a 1) (b 1))))
(pp a) # @[(27 "a") (68 "b") (42 "c") (31 "d")]
sortuvtcPlayground